Spring MVC - convert dates from user timezone to UTC

It is often recommended that from time to time they are stored in the database in UTC format and displayed to / from users in the local time zone.

I am trying to implement this pattern in a Spring MVC / Spring boot application, but could not find the documentation or examples. I use @DateTimeFormat annotations for java.util.Date attributes of @ModelAttribute form objects to make Spring parses / format dates.

Does Spring support this template? Something like strings Time in dangetime, which supports the Django time zone, would be nice. If not, is this not a cumbersome way to implement it? Or is there a better way to process / store data in a Spring MVC application?

At the moment, the application is used only in the UK, so currently I only need support for BST (summer time), and not different time zones for different users. However, user support in different time zones is a potential future.

+5
source share
1 answer

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); 
0
source

Source: https://habr.com/ru/post/1236051/


All Articles