In a flutter, I want to show the date picker according to Central European Standard Time. How can I do that?
Any help would be appreciated.
DateTime? newDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(1900),
lastDate: DateTime(2040),
helpText: 'Select Date',
cancelText: "CANCEL",
confirmText: "SAVE",
initialDatePickerMode: DatePickerMode.day,
selectableDayPredicate: _decideWhichDayToEnable,
builder: (context, child) {
return Theme(
data: Theme.of(context).copyWith(
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
primary: colorPrimary, // button text color
),
),
),
child: child!,
);
},
).then((value) {
if (value != null) {
setState(() {
date = DateFormat('dd-MM-yyyy').format(value);
isDateSelected = true;
_affiliateReward.currentState!.refreshData();
});
}
return null;
});
if (newDate == null) return;
setState(() {
dateFrom = newDate;
});
So, the above code is used to select the date for transaction. but Central European Standard time. How can we change that in flutter?
bool _decideWhichDayToEnable(DateTime day) {
if ((day.isAfter(DateTime.now().subtract(const Duration(days: 36500))) &&
day.isBefore(DateTime.now().add(const Duration(days: 0))))) {
return true;
}
return false;
}
If I understand you correctly this is not really showDatePicker
related but rather DateTime
. Inside your showDatePicker
you can set the initialDate
(you use DateTime.now()
thats why the timezone of you system devices gets used unless it is not anchored to UTC).
Since basic flutter DateTime
only supports local or UTC time you need to convert the selected timestamp to CET.
There are probably two approaches you could choose from:
Use a package with timezone support like this. You can then convert the selected timestamp into your desired timezone. This probably makes sense if you do a lot of different timezone related operations.
Do the timezone conversion by yourself:
You can take the selected value from your showDatePicker
- make sure that it is UTC with value.toUtc()
and add/subtract the specific time to convert into your desired timezone. For instance:
if (value != null) {
setState(() {
const utc = value.toUtc();
// Central Europe Standard Time is UTC + 01:00
var cetTimeStamp = utc.add(Duration(hours: 1)));
// do whatever you need
});
}
Since flutter datetime
only supports local time and UTC you do not explicitly know that this timestamp is CET. From an engineering point of view this is a quite unclean. Also if you send this object anywhere the timezone is still UTC. You can ofcourse also get the DateTime
as string and add the timezone to that string. How ever in such cases I'd recommened to use a third party package as I mentioned above.