Formatting and Parsing
Tempo supports formatting and parsing ISO 8601 strings, as well as locale-specific formats.
ISO 8601
All types have a toString method that returns an ISO 8601 date or period
string. For example:
defaultZoneId = 'America/New_York';
ZonedDateTime(2025, 1, 2, 3, 4, 5, 123456789).toString() ==
'2025-01-02T03:04:05.123456789-0500';
OffsetDateTime(2025, 1, 2, 3, 4, 5, 123456789).toString() ==
'2025-01-02T03:04:05.123456789-0500';
ZonedDateTime(2025, 1, 2, 3, 4, 5, 123456789).toInstant().toString() ==
'2025-01-02T08:04:05.123456789Z';
LocalDateTime(2025, 1, 2, 3, 4, 5, 123456789).toString() ==
'2025-01-02T03:04:05.123456789';
LocalDate(2025, 1, 2).toString() == '2025-01-02';
LocalTime(3, 4, 5, 123456789).toString() == '03:04:05.123456789';
Timespan(hours: 3, minutes: 1).toString() == 'PT3H1M';
Period(years: 1, months: 2, days: 3).toString() == 'P1Y2M3D';All types also have a parse constructor that parses an ISO 8601 date or period
string. For example:
LocalDateTime.parse('2025-01-02T13:30+0200') ==
LocalDateTime(2025, 1, 2, 3, 13, 30);
defaultZoneId = 'America/New_York';
ZonedDateTime.parse('2025-01-02T12:04Z') ==
ZonedDateTime(2025, 1, 2, 7, 4)Internationalization
While the ISO 8601 toString and parse functionality is useful for machines
(I like them for JSON encoding in particular), they’re less useful for
displaying to humans. For that, Tempo uses the
intl package. The local and absolute datetime
types have a format method that accepts a
DateFormat
and returns a formatted string. For example:
final fmt = DateFormat.yMMMMd('en_US');
LocalDate(2025, 6, 15).format(fmt) == 'June 6, 2025';If you’re using a locale other than
en_US, you will
likely need to perform some initialization steps before it will work. See the
DateFormat documentation
for more information.Don’t convert a Tempo type to
DateTime and call
DateFormat.format on it. Different objects convert to DateTime differently,
and some of those conversions could produce surprising results when formatted.