ConvertTime static method
DateTime
ConvertTime(
- DateTime dateTime,
- Location sourceTimeZone,
- Location destinationTimeZone
)
Converts the specified date and time from one time zone to another.
The date time to convert.
The source time zone.
The destination time zone.
Implementation
static DateTime ConvertTime(
DateTime dateTime,
Location sourceTimeZone,
Location destinationTimeZone,
) {
final bool sourceIsUtc = _IsUtcLocation(sourceTimeZone);
final bool kindMismatch = dateTime is TZDateTime
? !(dateTime.location == sourceTimeZone ||
(dateTime.isUtc && sourceIsUtc))
: (dateTime.isUtc && !sourceIsUtc);
if (kindMismatch) {
throw TimeZoneConversionException(
"Cannot convert ${DateTimeToXSDateTime(dateTime)} from time zone $sourceTimeZone to $destinationTimeZone.",
ArgumentException(
"The DateTime's kind does not match the source time zone.",
),
);
}
final TZDateTime source = dateTime is TZDateTime
? dateTime
: TZDateTime(
sourceTimeZone,
dateTime.year,
dateTime.month,
dateTime.day,
dateTime.hour,
dateTime.minute,
dateTime.second,
dateTime.millisecond,
dateTime.microsecond,
);
if (_IsUtcLocation(destinationTimeZone)) {
return DateTime.fromMicrosecondsSinceEpoch(
source.microsecondsSinceEpoch,
isUtc: true,
);
}
return TZDateTime.from(source, destinationTimeZone);
}