Dart| Flutter: How to Convert timestamp epoch to DateTime local and UTC| Flutter By Example

Timestamp alias Epoch timestamp or Unix timestamp is a long number that represents the number of milliseconds since 1970-01-01 PST. It is a Count of milliseconds elapsed since 1970-01-01 PST. Sometimes, you need to convert the timestamp to DateTime object in dart and flutter

You can check how to get Current Timestamp epcho

How to Convert Timestamp to DateTime in Dart and Flutter?

This example converts timestamp in milli and microseconds to DateTime

Let’s see how to get the Current timestamp in milli and microseconds.

void main() {
  print(DateTime.now()); //2022-10-30 11:51:16.566
  print(DateTime.now().millisecondsSinceEpoch); //1649571676566
  print(new DateTime.now().microsecondsSinceEpoch); //1649571676566000
}

DateTime provides two methods fromMicrosecondsSinceEpoch: Creates DateTime object from a given microseconds

DateTime DateTime.fromMicrosecondsSinceEpoch(int microsecondsSinceEpoch, {bool isUtc = false})

microsecondsSinceEpoch: The long number represents the microseconds elapsed epoch timestamp isUtc: default is false, returns local DateTime, true, returns UTC Date and time. fromMillisecondsSinceEpoch:

DateTime DateTime.fromMillisecondsSinceEpoch(int millisecondsSinceEpoch, {bool isUtc = false})

millisecondsSinceEpoch: The long number represents the milliseconds elapsed epoch timestamp isUtc: false, returns local DateTime, true, returns UTC Date and time.

Here is an example program parse timestamp to Local DateTime

void main() {
  var microSeconds = 1649571676566000;
  var date = new DateTime.fromMicrosecondsSinceEpoch(microSeconds);
  print(date); //2022-10-30 11:51:16.566

  var milliSeconds = 1649571676566;
  var date1 = DateTime.fromMillisecondsSinceEpoch(milliSeconds);
  print(date1); //2022-10-30 11:51:16.566
}

Output

2022-10-30 11:51:16.566
2022-10-30 11:51:16.566

Let’s see an example convert a timestamp to a Datetime UTC timestamp fromMicrosecondsSinceEpoch and fromMillisecondsSinceEpoch methods accept with isUtc:true argument to return UTC timezone

void main() {
  var microSeconds = 1649571676566000;
  var date = new DateTime.fromMicrosecondsSinceEpoch(microSeconds, isUtc: true);
  print(date); //2022-10-30 06:21:16.566Z

  var milliSeconds = 1649571676566;
  var date1 = DateTime.fromMillisecondsSinceEpoch(milliSeconds, isUtc: true);
  print(date1); //2022-10-30 06:21:16.566Z
}

Output:

2022-10-30 06:21:16.566Z
2022-10-30 06:21:16.566Z

In the output, the Z format in Datetime represents the ISO8601 Datetime standard for UTC dates and times.