While setting up a users birthdate, I get a date that is one day behind the stored date in the database.
For example
John Doe's birthdate: 1997-12-25T00:00:00 03:00
Flutter's DateTime.parse() date: 1997-12-24
Help needed please!
CodePudding user response:
My initial guess would be that the time is not being parsed either from or to the same time zone that you originally stored it in. The parse()
function can take an optional time zone (as described here) so maybe confirm the time zone is the same in every link of the chain.
Another thing to consider is Daylight savings, as that would could shift the time one way or another dependant on that.
It's possible that the offset for either of these factors is large enough to roll over to the day behind or the day before.
To get Flutter to parse the time as UTC, append a Z
to the end, for example:
DateTime.parse(datetime 'Z'); // UTC time
For any other time, you need to specify the hours difference, not a time zone, like so;
DateTime.parse(datetime ' 02:00'); // 2 hour difference ahead of UTC time
You also use .isUTC
to check if a date is interpreted as UTC and .toLocal()
to get the local time zone equivalent of the UTC date.
CodePudding user response:
Use DateTime value in the local time zone.
final datetimeParsed = DateTime.parse('1997-12-25T00:00:00 03:00').toLocal();
final DateFormat formatter = DateFormat('yyyy-MM-dd');
final String formatted = formatter.format(datetimeParsed);
print(formatted);