I'm developing a web application. When users sign up, their registration datetime needs to be stored accurately in the database and later displayed in a frontend viewed by site administrators.
I want to ensure that the displayed datetime is correct from the perspective of the user viewing the page, regardless of their timezone.
If a user registers at midday in New York, someone in London might see "user registered at 5pm today". This includes daylight saving time if applicable.
In Spring boot I use this annotation for storing the creation timestamp, and I am trying to determine if the class used here is appropriate:
@CreationTimestamp
@Column(name = "created_at")
public OffsetDateTime created_at;
But thinking about this I am very confused. Do I need to store a ZonedDateTime, or can I just actually store a timestamp (Instant) and then add the zone information later depending on who is making the request? Using the example above, this would be:
ZonedDateTime responseZonedDateTime = instant.atZone(ZoneId.of("Europe/London"));
The timezone here would come from the request handler, e.g.
@GetMapping
public String getUser(TimeZone timezone) { }
This seems like a lot of work and maybe there is a better solution?
(If this is relevant I am using PostgreSQL and the column type is TIMESTAMP WITH TIME ZONE.)
You can use Java's
Instantfor saving the timestamp. There is no need to save the timezone in the use-case you are describing. For displaying the timestamp in the timezone of the requesting user, you can use client libraries which are able to convert a UTC timestamp to the client timezone (i.e. dayjs, momentjs etc.).Saving the timezone only becomes relevant if you ever want to display/know the time of the user registering in their timezone.