Type conversions
Converting from one type to another is designed to be as consistent as possible, and the method names for doing so are the same no matter what you’re converting from. Note, however, that conversions will often lose information (such as time zones). See the API documentation for the specific method you’re calling for any caveats.
Dates and Times
These are the standard conversion methods for date and time types:
| Target | Conversion Method |
|---|---|
| DateTime | toDateTime() |
| Instant | toInstant() |
| OffsetDateTime | atOffset() |
| ZonedDateTime | inTimezone() |
| LocalDateTime | toLocal() |
| LocalDate | toLocal().date |
| LocalTime | toLocal().time |
These methods work even on the standard Dart
DateTime with an
extension. But with one exception: The method to convert to LocalDateTime is
toLocalDateTime. This is necessary because DateTime already has a toLocal
method.
Relative Times
These are the standard conversion methods for relative time types:
| Target | Conversion Method |
|---|---|
| Duration | toDuration() |
| Timespan | toTimespan() |
These methods also work on the standard Dart
Duration with an
extension.
Some examples:
ZonedDateTime(2025, 1, 2, 3, 4).toLocal() ==
LocalDateTime(2025, 1, 2, 3, 4);
LocalDateTime(2025, 12, 25, 6, 30).inTimeZone('America/Los_Angeles') ==
ZonedDateTime.withZoneId('America/Los_Angeles', 2025, 12, 25, 6, 30);Period, you’ll need to do what makes sense for your
application. (The only potentially legitimate reason for this is working with an
API you can’t change. If you need to for some other reason, you may need to
re-evaluate your approach. In either case, sticking with Duration and
Timespan may be the safest approach.)