Kinda Code
Home/Dart/Dart: Convert Timestamp to DateTime and vice versa

Dart: Convert Timestamp to DateTime and vice versa

Last updated: October 06, 2022

The examples below show you how to convert timestamp (also known as Unix time or Epoch time) to DateTime and vice versa in Dart (and Flutter as well). We can archive our goal without using any third-party plugins.

DateTime to TImestamp

The millisecondsSinceEpoch property of the DateTime class gives us the number of milliseconds since the “Unix epoch” 1970-01-01T00:00:00Z (UTC). This is the timestamp in milliseconds. If you want the timestamp in seconds, just divide the result by 1000.

Example:

// kindacode.com
// main.dart
void main() {
  final DateTime date1 = DateTime.now();
  final DateTime date2 = DateTime(2021, 8, 10); // August 10, 2021

  final timestamp1 = date1.millisecondsSinceEpoch;
  print('$timestamp1 (milliseconds)');
  final timestamp2 = date2.millisecondsSinceEpoch;
  print('$timestamp2 (milliseconds)');
}

Output:

1665069453177 (milliseconds)
1628528400000 (milliseconds)

Timestamp to DateTime

To get date time from a given timestamp, we can use the DateTime.fromMillisecondsSinceEpoch or DateTime.fromMicrosecondsSinceEpoch constructor.

Example:

// kindacode.com
// main.dart
void main() {
  const timestamp1 = 1627510285; // timestamp in seconds
  final DateTime date1 = DateTime.fromMillisecondsSinceEpoch(timestamp1 * 1000);
  print(date1);

  const timestamp2 = 1628528400;
  final DateTime date2 = DateTime.fromMillisecondsSinceEpoch(timestamp2 * 1000);
  print(date2);
}

We have to multiply the timestamp input by 1000 because DateTime.fromMillisecondsSinceEpoch expects milliseconds but we use seconds.

Output:

2021-07-29 05:11:25.000
2021-08-10 00:00:00.000

In case you use the DateTime.fromMicrosecondsSinceEpoch() method, don’t forget to multiply your timestamp input by 1.000.000.

You can find more information about the DateTime class in the official docs.

Final Words

We’ve gone through a few examples of converting a timestamp to a DateTime object and turning a DataTime object into a timestamp in Dart. If would like to learn more about Dart programming language and Flutter, take a look at the following articles:

You can also check out our Flutter category page, or Dart category page for the latest tutorials and examples.

Related Articles