Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter/Dart DateTime parsing UTC and converting to local

Tags:

dart

I am trying to parse a UTC Date string to DateTime and then parse it to local, however I am having troubles with converting it to the local time. In the UK it should be plus one, however when I print .isUtc it returns as false.

This is what I have now:

print(widget.asset.purchaseDate);
DateTime temp = DateTime.parse(widget.asset.purchaseDate);
print(temp.toLocal());
I/flutter (5434): 2020-05-07 21:29:00
I/flutter (5434): 2020-05-07 21:29:00.000
like image 749
Dev Daniel Avatar asked May 07 '20 22:05

Dev Daniel


1 Answers

You need to indicate a timezone to DateTime.parse, otherwise it assumes local time. From the dartdoc:

An optional time-zone offset part, possibly separated from the previous by a space. The time zone is either 'z' or 'Z', or it is a signed two digit hour part and an optional two digit minute part.

Since you know your string represents UTC, you can tell the parser by adding the Z suffix.

var temp = DateTime.parse(widget.asset.purchaseDate + 'Z');
print(temp.isUtc); // prints true
like image 157
Richard Heap Avatar answered Sep 30 '22 02:09

Richard Heap