Created
January 8, 2020 10:19
-
-
Save yrodiere/278996f865a9854e222aea58b5a7f26e to your computer and use it in GitHub Desktop.
ZonedDateTime with offset and zone ID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static java.time.temporal.ChronoField.DAY_OF_MONTH; | |
import static java.time.temporal.ChronoField.HOUR_OF_DAY; | |
import static java.time.temporal.ChronoField.MINUTE_OF_HOUR; | |
import static java.time.temporal.ChronoField.MONTH_OF_YEAR; | |
import static java.time.temporal.ChronoField.NANO_OF_SECOND; | |
import static java.time.temporal.ChronoField.SECOND_OF_MINUTE; | |
import static java.time.temporal.ChronoField.YEAR; | |
import java.time.ZonedDateTime; | |
import java.time.format.DateTimeFormatter; | |
import java.time.format.DateTimeFormatterBuilder; | |
import java.time.format.ResolverStyle; | |
import java.time.format.SignStyle; | |
import java.util.Locale; | |
import java.util.Objects; | |
class Scratch { | |
private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder() | |
.appendValue( YEAR, 4, 9, SignStyle.EXCEEDS_PAD ) | |
.appendLiteral( '-' ) | |
.appendValue( MONTH_OF_YEAR, 2 ) | |
.appendLiteral( '-' ) | |
.appendValue( DAY_OF_MONTH, 2 ) | |
.appendLiteral( 'T' ) | |
.appendValue( HOUR_OF_DAY, 2 ) | |
.appendLiteral( ':' ) | |
.appendValue( MINUTE_OF_HOUR, 2 ) | |
.optionalStart() | |
.appendLiteral( ':' ) | |
.appendValue( SECOND_OF_MINUTE, 2 ) | |
.optionalStart() | |
.appendFraction( NANO_OF_SECOND, 3, 9, true ) | |
.optionalEnd() | |
.optionalStart() | |
.appendOffsetId() | |
.optionalEnd() | |
.appendLiteral( '[' ) | |
.parseCaseSensitive() | |
.appendZoneRegionId() | |
.appendLiteral( ']' ) | |
.toFormatter( Locale.ROOT ) | |
.withResolverStyle( ResolverStyle.STRICT ); | |
public static void main(String[] args) { | |
ZonedDateTime withoutOffset = ZonedDateTime.parse( "2012-10-28T02:15:00[Europe/Berlin]", FORMATTER ); | |
ZonedDateTime withOffset = ZonedDateTime.parse( "2012-10-28T02:15:00+02:00[Europe/Berlin]", FORMATTER ); | |
if ( ! Objects.equals( withOffset, withoutOffset ) ) { | |
throw new RuntimeException( "1 failed" ); | |
} | |
withoutOffset = ZonedDateTime.parse( "2012-10-28T02:15:00[Europe/Berlin]", FORMATTER ); | |
withOffset = ZonedDateTime.parse( "2012-10-28T02:15:00+01:00[Europe/Berlin]", FORMATTER ); | |
// Will fail because the default offset during DST overlap when not specified is (in this case) +01:00 | |
// Note: this doesn't fail in JDK8 because of JDK-8066982. Use JDK11 instead. | |
if ( ! Objects.equals( withOffset, withoutOffset ) ) { | |
throw new RuntimeException( "2 failed" ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment