Hope this helps you, or at least becomes the point from which you can start.
It seems like the best way is to use the OffsetDateTime type to store dates. It is easy to convert dateTime values coming from the user in UTC:
OffsetDateTime createdOn = requestDto.getCreatedOn(); OffsetDateTime utc = createdOn.atZoneSameInstant(ZoneId.of("UTC"));
and vice versa (of course, you also need to store users timezone):
OffestDateTime eventDate = modelObject.getEventDate(); OffsetDateTime userTime = eventDate.atZoneSameInstant(ZoneId.of(userTimeZone));
To create a new date object in UTC , you can use a clock object:
OffestDateTime now = OffestDateTime.now(Clock.systemUTC()); ModelObject dto = new ModelObject(); dto.setEventDate(now);
And finally, if you do not need to display the offset, you can use the LocalDateTime type:
OffestDateTime eventDate = databaseModelObject.getEventDate(); LocalDateTime userTime = eventDate.atZoneSameInstant(ZoneId.of(userTimeZone)).toLocalDateTime()); ResponseDto response = new ResponseDto(); response.setEventDate(userTime);
source share