|
1 | 1 | # OffsetDateTime |
| 2 | + |
| 3 | +An `OffsetDateTime` is similar to a `ZonedDateTime` but with the key difference |
| 4 | +that an `OffsetDateTime` doesn't record a moment in a specific time zone, but instead |
| 5 | +as an offset from the [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time)[^utc] timezone. |
| 6 | + |
| 7 | +This is useful because timezones change their rules frequently. If you had to pick a representation |
| 8 | +of dates and times to store, this is a good default. |
| 9 | + |
| 10 | +```java |
| 11 | +import java.time.LocalDate; |
| 12 | +import java.time.LocalTime; |
| 13 | +import java.time.LocalDateTime; |
| 14 | +import java.time.ZonedDateTime; |
| 15 | +import java.time.ZoneId; |
| 16 | + |
| 17 | +class Main { |
| 18 | + void main() { |
| 19 | + var feb14 = LocalDate.of(2025, 2, 14); |
| 20 | + var fiveTwentyThree = LocalTime.of(5, 23, 0); |
| 21 | + var est = ZoneId.of("US/Eastern"); |
| 22 | + |
| 23 | + LocalDateTime localDateTime = LocalDateTime.of(feb14, fiveTwentyThree); |
| 24 | + ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, est); |
| 25 | + OffsetDateTime offsetDateTime = zonedDateTime.toOffsetDateTime(); |
| 26 | + |
| 27 | + System.out.println(offsetDateTime); |
| 28 | + } |
| 29 | +} |
| 30 | +``` |
| 31 | + |
| 32 | +You can get the current `OffsetDateTime` for the time zone your computer is running in |
| 33 | +with `OffsetDateTime.now()`. |
| 34 | + |
| 35 | +```java |
| 36 | +import java.time.OffsetDateTime; |
| 37 | + |
| 38 | +class Main { |
| 39 | + void main() { |
| 40 | + var now = OffsetDateTime.now(); |
| 41 | + |
| 42 | + System.out.println(now); |
| 43 | + } |
| 44 | +} |
| 45 | +``` |
| 46 | + |
| 47 | +And you can do the same for an arbitrary time zone by giving a `ZoneId` to |
| 48 | +`now`. Java knows the UTC offset for every time zone. |
| 49 | + |
| 50 | +```java |
| 51 | +import java.time.OffsetDateTime; |
| 52 | +import java.time.ZoneId; |
| 53 | + |
| 54 | +class Main { |
| 55 | + void main() { |
| 56 | + var now = OffsetDateTime.now(ZoneId.of("US/Eastern")); |
| 57 | + |
| 58 | + System.out.println(now); |
| 59 | + } |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | +[^utc]: UTC stands for "Coordinated Universal Time." No I don't know why the letters are in a different order [and at this point I'm too afraid to ask](https://knowyourmeme.com/memes/afraid-to-ask-andy). |
0 commit comments