Trending

World technology news

→
Java 8 java.time: scheduling shifts across daylight-saving changes
Software Engineering · 2014
Software Engineering2014

Java 8 java.time: scheduling shifts across daylight-saving changes

Turn a local shift time into an instant with Java 8, test the missing and repeated hours, and preserve the rule behind the schedule.

Archive retrospective · Topic year 2014

Developer's JournalPublished: Nov 27, 20266 min read
Reading progress0%
In this article
  1. A shift time starts as a local promise
  2. Use separate fields for local date, zone, and instant
  3. Read zero, one, or two offsets at a transition
  4. The next date and the next twenty-four hours can differ
  5. Preserve uncertainty when migrating old dates
  6. Check what the operator was promised

A shift time starts as a local promise

A field team announces maintenance at 02:30 on Sunday. The scheduler has to turn it into one instant for a job queue. On some dates that clock reading does not occur; on others it occurs twice. An automatic conversion can silently change the promise. Java 8 introduced java.time in the 2014 period, giving the system distinct types for these meanings. We use synthetic appointments with Berlin's transitions in that year. Save the date and time people requested in the location where the work is planned. Save the resolved instant for execution. A timestamp by itself leaves the recurring intention ambiguous. Asking when a completed task ran and when the same duty should run next week are separate questions.

Technical referencesJava SE 8 java.time ↗

Use separate fields for local date, zone, and instant

A LocalDateTime has a date and clock reading without a zone. A ZoneId such as Europe/Berlin gives access to rules that produce offsets on particular dates. An offset such as +01:00 describes a relationship to UTC, but cannot express a location's future transitions. An Instant provides a common point on the execution timeline. The same instant displayed in two offices can have different local times. An interface should decide whether it is showing the maintenance location or the person viewing it. A schedule detail could show the site time first and expose the UTC instant alongside diagnostics. Keep the zone identifier with a recurring schedule so future occurrences may be resolved against the appropriate rules.

Application flowConceptual sketch · summary of the article's technical flow

Read zero, one, or two offsets at a transition

ZoneRules.getValidOffsets returns the offsets usable for a local clock reading. At 02:30 on March 30, 2014 in Berlin, that list is empty. During the forward transition the clock skips the proposed time. Some businesses may allow moving to a later time. Our policy asks the operator to choose another time. The repeated 02:30 on October 26, 2014 is valid with two offsets, corresponding to 00:30Z and 01:30Z. Display both choices and record what the operator selected. ZonedDateTime.ofStrict checks that the chosen offset is valid for that local time in that zone. An ordinary day yields one choice. Put all three cases in the test matrix and check the user-facing response.

ZoneId zone = ZoneId.of("Europe/Berlin");
LocalDateTime missing = LocalDateTime.of(2014, 3, 30, 2, 30);
LocalDateTime repeated = LocalDateTime.of(2014, 10, 26, 2, 30);
System.out.println(zone.getRules().getValidOffsets(missing));  // []
List<ZoneOffset> choices = zone.getRules().getValidOffsets(repeated);
for (ZoneOffset offset : choices) {
    System.out.println(ZonedDateTime.ofStrict(repeated, offset, zone).toInstant());
}
// 2014-10-26T00:30:00Z
// 2014-10-26T01:30:00Z

The next date and the next twenty-four hours can differ

A task requested at 09:00 each day advances on the local calendar. A retry expected exactly twenty-four hours after a failed attempt advances by elapsed time. In Berlin, from 09:00 on October 25 to 09:00 the next day took twenty-five hours in 2014. Adding twenty-four hours gives 08:00 after the clocks change. The choice follows the work rule, not the convenience of an API method. Calculate scheduled future local occurrences using the same policy for gaps and overlaps at every affected date. Keep enough of the original rule to recompute upcoming work if the time zone database changes. A job that has already completed preserves its recorded execution instant as an observation.

ZonedDateTime start =
    ZonedDateTime.of(2014, 10, 25, 9, 0, 0, 0, zone);
ZonedDateTime nextDay = start.plusDays(1);
ZonedDateTime in24Hours = start.plusHours(24);
System.out.println(nextDay.toLocalTime());   // 09:00
System.out.println(in24Hours.toLocalTime()); // 08:00
System.out.println(Duration.between(start, nextDay).toHours()); // 25

Preserve uncertainty when migrating old dates

Plain strings without a zone are the riskiest source. A string representing 02:30 on October 26 in Berlin does not establish which occurrence the author intended. Today's account timezone may differ from the job's former location. Seek a source facility record and timestamped device evidence that can resolve ambiguity. Put unresolved records into a separate review state instead of inventing a single offset for every case. For new one-time jobs, retain requested local date and time, zone, selected offset, and resulting instant. Retain the recurrence rule separately when one exists. Rehearse a timezone data update and compare sample future jobs before and after. This also tests any adapters converting old date fields into the Java 8 model.

Check what the operator was promised

Choose three fixture dates: a normal day, a gap, and an overlap. Assert one, zero, and two choices respectively. Save an overlap choice and open the result from another zone. The appointment still belongs to the original facility's time zone. Restart the job queue after the transition and verify the same scheduled job identity is not executed twice. If reminders and execution each resolve time, test both. Java 8 Clock can pin the current instant for tests that would otherwise behave differently near midnight. The durable benefit of this period API is an explicit purpose for each time value. The system no longer has to guess whether a shared string represents intent, a rule, or an observation.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

How would you measure this development's real-world impact?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.