Time in Dart

Here’s the Dart translation of the Go code example for handling time and durations:

Our first program demonstrates Dart’s support for times and durations. Here’s the full source code:

import 'dart:core';

void main() {
  void p(Object obj) => print(obj);

  // We'll start by getting the current time.
  var now = DateTime.now();
  p(now);

  // You can create a DateTime object by providing the year, month, day, etc.
  // Times are always associated with a time zone.
  var then = DateTime.utc(2009, 11, 17, 20, 34, 58, 651387);
  p(then);

  // You can extract the various components of the time value as expected.
  p(then.year);
  p(then.month);
  p(then.day);
  p(then.hour);
  p(then.minute);
  p(then.second);
  p(then.millisecond);
  p(then.microsecond);
  p(then.timeZoneName);

  // The weekday is also available.
  p(then.weekday);

  // These methods compare two times, testing if the first occurs before, 
  // after, or at the same time as the second, respectively.
  p(then.isBefore(now));
  p(then.isAfter(now));
  p(then.isAtSameMomentAs(now));

  // The difference method returns a Duration representing
  // the interval between two times.
  var diff = now.difference(then);
  p(diff);

  // We can compute the length of the duration in various units.
  p(diff.inHours);
  p(diff.inMinutes);
  p(diff.inSeconds);
  p(diff.inMilliseconds);

  // You can use add to advance a time by a given duration,
  // or subtract to move backwards by a duration.
  p(then.add(diff));
  p(then.subtract(diff));
}

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

$ dart run time_example.dart
2023-06-13 10:15:30.123456
2009-11-17 20:34:58.651387Z
2009
11
17
20
34
58
651
387
UTC
2
true
false
false
118055:40:31.472069
118055
7083340
424700431
424700431472069
2023-06-13 10:15:30.123456Z
1996-04-23 06:54:27.179318Z

This example demonstrates how to work with dates, times, and durations in Dart. The DateTime class is used for representing a point in time, while the Duration class represents a span of time. These classes provide methods for creating, manipulating, and comparing times and durations.

Note that Dart uses milliseconds for its time resolution, unlike Go which uses nanoseconds. Also, Dart’s DateTime doesn’t have a separate nanosecond field, so we’ve used microseconds (which includes milliseconds) as the closest equivalent.

Next, we’ll look at the related idea of time relative to the Unix epoch.