我想要什么:我只想獲取 DateTime 格式的 startDate 和 endDate,以便我可以找到兩個日期之間的天數差異。相反,我以字串格式獲取 startDate 和 endDate。
我的代碼:
void _onSelectionChanged(DateRangePickerSelectionChangedArgs args) {
print("Printing start date before setstate");
print(startDate);
setState(() {
if (args.value is PickerDateRange) {
_range = DateFormat('dd/MM/yyyy')
.format(args.value.startDate)
.toString()
' - '
DateFormat('dd/MM/yyyy')
.format(args.value.endDate ?? args.value.startDate)
.toString();
} else if (args.value is DateTime) {
_selectedDate = args.value.toString();
} else if (args.value is List<DateTime>) {
_dateCount = args.value.length.toString();
} else {
_rangeCount = args.value.length.toString();
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.teal[50],
body: Container(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.40,
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25.0)),
child: SfDateRangePicker(
view: DateRangePickerView.month,
monthViewSettings: DateRangePickerMonthViewSettings(
showTrailingAndLeadingDates: true),
selectionColor: Colors.teal,
startRangeSelectionColor: Colors.teal[400],
endRangeSelectionColor: Colors.teal[400],
rangeSelectionColor: Colors.teal[200],
rangeTextStyle:
const TextStyle(color: Colors.white, fontSize: 15),
onSelectionChanged: _onSelectionChanged,
selectionMode: DateRangePickerSelectionMode.range,
initialSelectedRange: PickerDateRange(
DateTime.now(),
DateTime.now().add(
const Duration(days: 5),
),
),
),
),
),
我嘗試過的:我嘗試像這樣列印 startDate:
print(args.value.startDate);
final DateFormat formatter = DateFormat('yyyy-MM-dd');
final String formattedStartDate =
formatter.format(args.value.startDate);
print(formattedStartDate); // printing only date
我成功獲得了日期,但它是 String 型別而不是 DateTime 型別。
uj5u.com熱心網友回復:
如果要從 String 獲取 DateTime 物件,請執行以下操作:
DateFormat('yyyy-MM-dd').parse('some string date')
uj5u.com熱心網友回復:
嘗試在方法差異中使用所需格式的日期。
var berlinWallFell = DateTime(1989, DateTime.november, 9);
var dDay = DateTime(1944, DateTime.june, 6);
Duration difference = berlinWallFell.difference(dDay);
assert(difference.inDays == 16592);
鏈接:https : //api.flutter.dev/flutter/dart-core/DateTime/difference.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/330703.html
上一篇:在Flutter中創建復選框
