withZoneSameInstant method
Converts this date-time to the same instant in a different timezone.
The instant in time remains the same, but the local date-time values change to reflect the new timezone.
Example:
final nyTime = ZonedDateTime.parse('2023-12-25T15:00:00-05:00[America/New_York]');
final londonTime = nyTime.withZoneSameInstant(ZoneId.of('Europe/London'));
final tokyoTime = nyTime.withZoneSameInstant(ZoneId.of('Asia/Tokyo'));
print('New York: $nyTime'); // 15:00 EST
print('London: $londonTime'); // 20:00 GMT (5 hours ahead)
print('Tokyo: $tokyoTime'); // 05:00 JST next day (14 hours ahead)
Implementation
ZonedDateTime withZoneSameInstant(ZoneId zone) {
if (_zone == zone) return this;
// Convert to UTC first
final utcDateTime = _localDateTime.minus(_offset);
// Then convert to target timezone
final offsetData = TimezoneDatabase.getOffsetForZone(zone.id, utcDateTime);
final targetDateTime = utcDateTime.plus(offsetData.offset);
return ZonedDateTime._(targetDateTime, zone, offsetData.offset, offsetData.isDst);
}