Epoch in Dart

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Dart.

import 'dart:core';

void main() {
  // Use DateTime.now() to get the current time
  var now = DateTime.now();
  print(now);

  // Get elapsed time since the Unix epoch in seconds,
  // milliseconds or microseconds
  print(now.millisecondsSinceEpoch ~/ 1000);
  print(now.millisecondsSinceEpoch);
  print(now.microsecondsSinceEpoch);

  // You can also convert integer milliseconds or microseconds
  // since the epoch into the corresponding DateTime
  print(DateTime.fromMillisecondsSinceEpoch(now.millisecondsSinceEpoch));
  print(DateTime.fromMicrosecondsSinceEpoch(now.microsecondsSinceEpoch));
}

To run the program, save it as epoch.dart and use the dart command:

$ dart run epoch.dart
2023-05-31 12:34:56.789012
1685535296
1685535296789
1685535296789012
2023-05-31 12:34:56.789
2023-05-31 12:34:56.789012

In Dart, we use the DateTime class to work with dates and times. The DateTime.now() method gives us the current date and time.

To get the elapsed time since the Unix epoch, we use the millisecondsSinceEpoch property. Dart doesn’t have built-in methods for seconds or nanoseconds since epoch, so we divide by 1000 to get seconds, and use microsecondsSinceEpoch for higher precision.

To convert back from milliseconds or microseconds to a DateTime object, we use DateTime.fromMillisecondsSinceEpoch() and DateTime.fromMicrosecondsSinceEpoch() respectively.

Next, we’ll look at another time-related task: time parsing and formatting.