Reputation: 580
Built a basic system which allows a user to Schedule a meeting with person A, B, C on some date/time.
I wanted to sanity check that our solution will work across DST changes.
The two key classes are:
User
- holds the user's ZoneId
so Europe/Paris
, Asia/Tokyo
etc.Event
- holds the LocalDateTime
of the scheduled event eg. 2018-05-04T10:00:00.000
and the ZoneId
of the user at the time of the event's creation eg. Europe/Paris
.We then stick the event in our scheduler:
import org.springframework.scheduling.TaskScheduler;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
public class MyScheduler {
private final TaskScheduler executor;
...
public void schedule(Event event) {
...
ZonedDateTime scheduledAt = ZonedDateTime.of(event.getScheduledAt(), event.getScheduledAtTimeZone());
if (scheduledAt.isAfter(ZonedDateTime.now(ZoneId.systemDefault()))) {
executor.schedule(task, Date.from(scheduledAt.toInstant()));
}
}
}
If I'm correct the above code should start the event set for Friday 10am Europe/Paris
no matter whether the clocks are UTC+1 or UTC+2.
Does the above approach seem sane?
I've also noticed that the ZonedDateTime
class holds an offset in addition to the time and zone eg. 2018-05-02T20:46:03.002+01:00[Europe/London]
. The only reason (I can think of) to hold the offset would be to know whether the user created the event during daylight savings or not.
That being the case is there any benefit to our system storing the offset or are we good with just the local event time and the zone it was created in?
Upvotes: 3
Views: 253
Reputation: 86324
The only real issue I can think of is the corner case where the event happens in the autumn when the clock is moved backward, then the LocalDateTime
may be ambiguous even knowing the zone.
Instant
is generally recommended for time-zone neutral points in time, so unless it’s a strict requirement to know the time-zone in which the event was created, I would use this. Also even if that is a requirement since you can still keep the ZoneId
beside it. It would also make your code a bit simpler. The other sane option is a ZonedDateTime
for the scheduled time; it appeals less to me.
Upvotes: 1