Home > Back-end >  Can I parse an OffsetDateTime from an HTML form without asking for the offset?
Can I parse an OffsetDateTime from an HTML form without asking for the offset?

Time:07-19

I'm trying to receive a date from a JSP form where a user enters a date and time for an event to start. Each event will occur at that instant (i.e. it will be represented by an OffsetDateTime object so it can be stored in my DB). It seems to me that my options for getting a date/ time from the user so far are to either use <form:input type="date"/> & <form:input type="time"/> together or <form:input type="datetime-local"/>, neither of which supply the offset necessary to accurately represent the moment the event will occur. Is there a way to gather this offset without explicitly prompting the user for their time zone?

My concern is the following scenario: A user in another time zone supplies a date & a time for an event. My controller then uses this date/ time to produce a java.time object to be stored in the database. However, without knowing what the user's offset is, I have no way to know the correct adjustment to make to the timestamp and it will instead be interpreted as my local time.

CodePudding user response:

You could try to get an offset from the browser as noted in the Comments.

But really you should verify the intended time zone with the user.

Time zones are named in the format of Continent/Region, such as Europe/Paris or Africa/Tunis. So you can easily make a hierarchical zone picker.

For critical tasks, such as the user inputting an event to take place at a certain date and time, you should not rely on defaults alone. For example, your user could be a German businesswoman residing in France, currently at a conference in Tokyo Japan, inputting an event to take place in Chicago US. Neither her home time zone, nor her current location will indicate the event is being presented for the time zone America/Chicago.

String userSelectedContinent = … ;
String userSelectedRegion = … ;
String zoneName = String.join( "/" , userSelectedContinent , userSelectedRegion ) ;
ZoneId z = null ;
try {
    z = ZoneId.of( 
} catch ( DateTimeException e ) {
    … 
} catch ( ZoneRulesException  e ) {
    …
}
  • Related