简体   繁体   中英

Proper Java class to represent a date in UTC timezone

I have a Spring Boot (Jackson marshalling) REST api application where I will be treating all date/times (start and end times for schedules) as being in the UTC timezone. What is the "proper" Java class that I should use in my code for holding these date/times? I feel like we should be explicit and use OffsetDateTime with the internal Timezone as UTC just in case we will need to be switching timezones or printing/logging the dates etc.

Thoughts? Would LocalDateTime be ok to use for simplicity since they will all be UTC?

You need to use ZonedDateTime . LocalDateTime doesn't have any zone information (not even UTC).

To work with jackson, you need to include jsr310 library for automatic serilization / deserialization of Java 8 Date / Time classes.

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

Also by default ObjectMapper parses date / time in UTC Zone which will be helpful in your case. jsr310 module will be automatically registered by Spring boot. If you want to create your own ObjectMapper you need to use

ObjectMapper mapper = new ObjectMapper();

// will register all modules on classpath
mapper.findAndRegisterModules();

// only jsr310 module will be registered
mapper.registerModule(new JavaTimeModule());

If choosing UTC as a time zone neutral representation — which is a good thought — I suggest Instant from java.time . An Instant is a point in time. Conceptually it doesn't have a time zone. It sounds like this would be an advantage. You can switch time zones all that you want later, and your points in time will stay the same. An Instant can be parsed from an ISO 8601 string in UTC using its parse method (for example 2018-12-31T23:37:45.975Z ). And its toString produces the same, still always in UTC.

If you want an explicit representation of the fact that your date-time is in UTC, you may use an OffsetDateTime with offset ZoneOffset.UTC . Since you say that your times are always in UTC, I would consider it redundant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM