Skip to content
AgileLogics
4 min read

Dates and Times

Prerequisites: Classes and objects

Dart represents a moment in time with DateTime and an amount of time with Duration.

Example

void main() {
  final start = DateTime.utc(2025, 1, 31, 9, 30);
  print(start);
  print(start.toIso8601String());
  print(start.weekday == DateTime.friday);

  final later = start.add(const Duration(days: 30, hours: 2));
  print(later);

  final christmas = DateTime.utc(2025, 12, 25);
  print(christmas.difference(start).inDays);

  print(DateTime.parse('2025-03-01T12:00:00Z').month);
  print(start.isBefore(christmas));
  print(DateTime.fromMillisecondsSinceEpoch(0, isUtc: true));
}

Expected output

2025-01-31 09:30:00.000Z
2025-01-31T09:30:00.000Z
true
2025-03-02 11:30:00.000Z
327
3
true
1970-01-01 00:00:00.000Z
  • DateTime.utc(...) creates a UTC time; DateTime(...) uses the device's local time zone; DateTime.now() is the current local time.
  • difference returns a Duration; inDays counts whole days, so the partial day after 09:30 on Christmas Eve isn't included.
  • DateTime.fromMillisecondsSinceEpoch converts a Unix timestamp (in milliseconds). The Unix Epoch Converter translates timestamps back and forth.

Durations

void main() {
  const timeout = Duration(minutes: 1, seconds: 30);
  print(timeout.inSeconds);
  print(timeout * 2);
}
90
0:03:00.000000

Formatting for people

For dates shown to users in their own language and format, use the intl package: DateFormat.yMMMd().format(date) gives, for example, Jan 31, 2025 in US English.

Common mistakes

  • Mixing local and UTC times. Store and compare in UTC (toUtc()), and convert to local time only for display.
  • Adding Duration(days: 30) when you mean "one month later" — months have different lengths. Build the date explicitly instead: DateTime.utc(d.year, d.month + 1, d.day).