Search code examples
dartdatetimeutclocaltime

How to convert an UTC datetime string into a local datetime in Dart?


I got this value from an API 2022-03-15T02:33:53.488427, it is a string which represents a UTC timestamp, my current zone time is UTC-5, I'm trying this code:

createdAt = DateTime.tryParse('2022-03-15T02:33:53.488427').toLocal();

But createdAt contains the same datetime like the original string, What I'm missing?


Solution

  • the string 2022-03-15T02:33:53.488427 does not include a timezone. So to tell Dart that you want this to be UTC time, then append a "Z" to the string. Then it knows that it is Zulu time. Otherwise it's going to assume that you are in local time when it parses it. try

    createdAt = DateTime.tryParse('2022-03-15T02:33:53.488427Z').toLocal();
    

    Use print(createdDate?.timeZoneName) to confirm UTC or your local