Type conversions

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:

TargetConversion Method
DateTimetoDateTime()
InstanttoInstant()
OffsetDateTimeatOffset()
ZonedDateTimeinTimezone()
LocalDateTimetoLocal()
LocalDatetoLocal().date
LocalTimetoLocal().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:

TargetConversion Method
DurationtoDuration()
TimespantoTimespan()

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 has no associated conversion methods, because it doesn’t represent a fixed amount of time. There’s no general way to make such a conversion. If you must convert something to a 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.)