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.
To run the program, save it as epoch.dart
and use the dart
command:
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.