Skip to main content

WorldClock and JSR310

With JSR310 (Date and Time API) in Java 8 and the small 0.7 release of WorldClock done, I can update WorldClock to the new API.

First the time used for day and night drawing:

(in WorldClockBoard)

PreJava8:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”));
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH) + 1; int year = cal.get(Calendar.YEAR);
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);

Java8:

OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
int day = now.getDayOfMonth();
int month = now.getMonthValue(); int year = now.getYear();
int hours = now.getHour();
int minutes = now.getMinute();
int seconds = now.getSecond();

Next the timezone and time formatting for a city:

(in City)

PreJava8:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
//…

private final TimeZone tz;
private final Calendar cal;
private final SimpleDateFormat sdf = new SimpleDateFormat(“HH:mm”);
//…

// in the constructor
tz = TimeZone.getTimeZone(tzName); cal = Calendar.getInstance(tz);
sdf.setTimeZone(tz);
//…

// in the paint method
cal.setTime(new Date());
final String time = sdf.format(cal.getTime());

Java8:

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
//…

private final DateTimeFormatter formatter;
//…

// in the constructor
formatter = DateTimeFormatter.ofPattern(“HH:mm”).withZone(ZoneId.of(tzName)); //…

// in the paint method
final String time = formatter.format(Instant.now());

And the refresh ticker:

(in WorldClockPanel)

PreJava8:

private long last = 0;
//…

long now = System.currentTimeMillis() / 60000;
if (now > last)

Java8:

//(a bit verbose):
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
//…

private final Clock minuteClock = Clock.tickMinutes(ZoneId.systemDefault());
private Instant last = Instant.EPOCH;
//…

Instant now = minuteClock.instant();
if (now.isAfter(last))