Flutter/Dart DateTime parsing UTC and converting to local

Viewed 11045

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
2 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

While @Richard Heap's answer stands I'd like DateTime.parseUtc() to exist.

If there will be a day when dart allows static extension methods here is an implementation that would work:

extension DateTimeExtension on DateTime {
  static DateTime parseUtc(String formattedDate) => DateTime.parse('${formattedDate}z');

  static DateTime? tryParseUtc(String? formattedDate) {
    if (formattedDate != null) {
      return DateTime.tryParse('${formattedDate}z');
    }
    return null;
  }
}

Currently you'd have to use it with the extension classes name, like so: DateTimeExtension.parseUtc(someDate)
or
DateTimeExtension.tryParseUtc(someOtherDate)

I think the latter is more useful where someOtherDate is nullable

Related