Dart: Convert Timestamp to DateTime and vice versa

Last updated on July 29, 2021 A Goodman Loading... Post a comment

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 as 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:

// 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:

1627511340786 (milliseconds)
1628528400000 (milliseconds)

Timestamp to DateTime

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

Example:

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

  final 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

Final Words

We’ve gone through a few examples of converting timestamp to DateTime and turning DataTime into 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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like