Time Formatting Parsing in Dart

Dart supports time formatting and parsing via the intl package and the DateTime class.

import 'package:intl/intl.dart';

void main() {
  // Here's a basic example of formatting a time
  // according to ISO 8601, which is similar to RFC3339.
  var now = DateTime.now();
  print(now.toIso8601String());

  // Time parsing uses DateFormat from the intl package.
  var dateFormat = DateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
  var t1 = dateFormat.parse("2012-11-01T22:08:41+0000");
  print(t1);

  // DateFormat allows for custom formatting patterns.
  print(DateFormat('jm').format(now)); // 6:00 PM
  print(DateFormat('EEE MMM d HH:mm:ss yyyy').format(now)); // Tue Apr 15 18:00:15 2014
  print(DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(now)); // 2014-04-15T18:00:15.161-0700

  var form = DateFormat("h mm a");
  var t2 = form.parse("8 41 PM");
  print(t2);

  // For purely numeric representations you can also
  // use string interpolation with the extracted
  // components of the DateTime value.
  print('${now.year}-${now.month.toString().padLeft(2, '0')}-'
      '${now.day.toString().padLeft(2, '0')}T'
      '${now.hour.toString().padLeft(2, '0')}:'
      '${now.minute.toString().padLeft(2, '0')}:'
      '${now.second.toString().padLeft(2, '0')}-00:00');

  // parse will throw a FormatException on malformed input
  try {
    DateFormat('EEE MMM d HH:mm:ss yyyy').parse("8:41PM");
  } catch (e) {
    print(e);
  }
}

To run this program, you’ll need to add the intl package to your pubspec.yaml file:

dependencies:
  intl: ^0.17.0

Then run:

$ dart pub get
$ dart run main.dart
2023-05-10T15:30:45.123456
2012-11-01 22:08:41.000Z
3:30 PM
Wed May 10 15:30:45 2023
2023-05-10T15:30:45.123-0700
2023-05-10 20:41:00.000Z
2023-05-10T15:30:45-00:00
FormatException: Trying to read HH from 8:41PM at position 0

In Dart, we use the DateTime class for working with dates and times. The intl package provides the DateFormat class for parsing and formatting dates in various formats. Unlike Go, Dart doesn’t use example-based layouts, but instead uses pattern strings similar to those used in Java’s SimpleDateFormat.

The DateTime class provides methods like toIso8601String() for standard formatting, and you can use DateFormat for custom formatting and parsing. Error handling for parsing is done through exceptions rather than returned error values.