ZonedDateTime.fromDateTime constructor
Creates a ZonedDateTime from a standard DateTime object.
The DateTime is assumed to be in the specified timezone. If no timezone is provided, it defaults to UTC.
Example:
final dateTime = DateTime(2023, 12, 25, 15, 30);
final zonedUtc = ZonedDateTime.fromDateTime(dateTime); // Assumes UTC
final zonedEst = ZonedDateTime.fromDateTime(dateTime, ZoneId.of('EST'));
print('As UTC: $zonedUtc');
print('As EST: $zonedEst');
Represents a date-time with timezone information.
This class combines a LocalDateTime with timezone information to represent a complete date-time with offset from UTC. Unlike Java's implementation, this version includes a built-in timezone database for common timezones without requiring external dependencies.
Key Features:
- Immutable: All operations return new instances
- Timezone Aware: Handles UTC offsets and common timezone names
- DST Support: Basic daylight saving time handling for major timezones
- Conversion: Easy conversion between timezones
- Formatting: ISO 8601 compliant string representation
Supported Timezone Formats:
- UTC Offsets:
+05:00
,-08:00
,Z
(for UTC) - Timezone Names:
EST
,PST
,GMT
,CET
, etc. - Full Names:
America/New_York
,Europe/London
, etc.
Usage Examples:
// Create from current time
final now = ZonedDateTime.now();
final nowInParis = ZonedDateTime.now(ZoneId.of('Europe/Paris'));
// Create with specific date-time
final localDT = LocalDateTime.of(2023, 12, 25, 15, 30);
final christmas = ZonedDateTime.of(localDT, ZoneId.of('America/New_York'));
// Parse from string
final parsed = ZonedDateTime.parse('2023-12-25T15:30:00+01:00[Europe/Paris]');
// Convert between timezones
final utc = christmas.toUtc();
final tokyo = christmas.withZoneSameInstant(ZoneId.of('Asia/Tokyo'));
// Arithmetic operations
final tomorrow = christmas.plusDays(1);
final nextHour = christmas.plusHours(1);
Timezone Database:
This implementation includes a comprehensive timezone database with:
- Major world timezones with their UTC offsets
- Daylight saving time rules for common timezones
- Historical timezone data for accurate conversions
- Support for both abbreviated and full timezone names
Implementation
factory ZonedDateTime.fromDateTime(DateTime dateTime, [ZoneId? zone]) {
zone ??= ZoneId.UTC;
final localDateTime = LocalDateTime.fromDateTime(dateTime);
return ZonedDateTime.of(localDateTime, zone);
}