What i want: I want to get only the startDate and endDate in DateTime format so that i can find the difference of days between the two dates. Instead i'm getting startDate and endDate in String format.
My code:
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),
),
),
),
),
),
What i've tried: I tried to print the startDate like this:
print(args.value.startDate);
final DateFormat formatter = DateFormat('yyyy-MM-dd');
final String formattedStartDate =
formatter.format(args.value.startDate);
print(formattedStartDate); // printing only date
and i successfully got the date but it is the String type instead of DateTime type.
CodePudding user response:
If you want to get a DateTime object from String do that:
DateFormat('yyyy-MM-dd').parse('some string date')
CodePudding user response:
Try to use the dates in a required format in the method difference.
var berlinWallFell = DateTime(1989, DateTime.november, 9);
var dDay = DateTime(1944, DateTime.june, 6);
Duration difference = berlinWallFell.difference(dDay);
assert(difference.inDays == 16592);
Link: https://api.flutter.dev/flutter/dart-core/DateTime/difference.html