Skip to content

Instantly share code, notes, and snippets.

@DK15
Last active April 8, 2020 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DK15/2a4835995aeaa01deb0b1d720d25edd6 to your computer and use it in GitHub Desktop.
Save DK15/2a4835995aeaa01deb0b1d720d25edd6 to your computer and use it in GitHub Desktop.
Converting timestamp in specific format in Dart
/*
Many a times we receive timestamp from an api which is in this format -> 2020-04-08T12:20:40.000Z. We ofcourse can't use
this date as is in the UI. Hence, we first need to convert it into a readable or specific format.
*/
// Notice the `T` in the given date. It acts as a separator between `date` and `time` and doesn't hold any significance. Hence we will separate the given date using `substring()` method as below:
var str = "2020-04-08T12:20:40.000Z";
var newStr = str.substring(0,10) + ' ' + str.substring(11,23);
print(newStr); // 2020-04-08 12:20:40.000
// The last letter in the given date, `Z` indicates UTC or `Zero` timezone offset by 0 from UTC. We will leave out that letter using `substring()` as shown above.
// Convert String into DateTime object
DateTime dt = DateTime.parse(newStr);
// Specify the format in which we want the DateTime object need to be converted and then format it.
print(DateFormat("EEE, d MMM yyyy HH:mm:ss").format(dt)); // Wed, 8 Apr 2020 12:20:40
/* Final output:
Date to convert : 2020-04-08T12:20:40.000Z
Specified format: EEE, d MMM yyyy HH:mm:ss
Result : Wed, 8 Apr 2020 12:20:40
*/
// Originally posted as an answer on StackOverflow question: https://stackoverflow.com/questions/61069464/how-to-format-this-date-2019-04-05t140051-000z-in-flutter/61074152#61074152
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment