Java 8 Date & Time API Cheat Sheet

Leave a comment
Dev

For a long time now the excellent Joda-Time library has been the de facto date and time API for Java. Like SLF4J or Guava it is one of those dependencies that I seem to add by default to any new project but since the release of Java 8 users are asked to migrate to the new java.time API. Finally Java has a date and time API it doesn’t need to be ashamed of.

This new API is heavily influenced by the good design decisions of Joda-Time and much of its usage is similar but with years of writing Joda-Time code under my fingers I still find myself checking the new Javadoc from time to time for the subtle differences.

Here is a short list of some common date/time tasks using the new API. Interoperability with the old Date class will often be a requirement for the near future so included are a couple of examples converting from java.util.Date and java.sql.Date to java.time.

// Convert java.util.Date to java.time.ZonedDateTime
Date now = new Date();
ZonedDateTime utc = ZonedDateTime.ofInstant(now.toInstant(), ZoneOffset.UTC);
ZonedDateTime auckland = ZonedDateTime.ofInstant(now.toInstant(), ZoneId.of("Pacific/Auckland"));
ZonedDateTime plusOne = ZonedDateTime.ofInstant(now.toInstant(), ZoneOffset.of("+1"));

// Convert java.time.ZonedDateTime to java.util.Date
ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC);
Date now = Date.from(utc.toInstant());

// Convert java.time.ZonedDateTime to milliseconds from Epoch (java.util.Date#getTime)
ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC);
utc.toInstant.toEpochMilli();

// Start of today
ZonedDateTime startOfToday = LocalDate.now().atStartOfDay(ZoneOffset.UTC);

// Start of this week (Monday)
ZonedDateTime startOfWeek = LocalDate.now().atStartOfDay(ZoneId.of("Europe/London")).with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));

// Start of this month
ZonedDateTime startOfMonth = LocalDate.now().atStartOfDay(ZoneOffset.UTC).with(TemporalAdjusters.firstDayOfMonth());

// Days between dates
LocalDate today = LocalDate.now();
LocalDate threeDaysAgo = today.minusDays(3);
long days = ChronoUnit.DAYS.between(threeDaysAgo, today);

// java.sql.date to java.time.Instant
java.sql.Date sqlDate = new java.sql.Date(1446853831381L);
Instant i = Instant.ofEpochMilli(sqlDate.getTime());

//Can also convert to LocalDate directly
sqlDate.toLocalDate();

You can drop Joda-Time from your Scala apps running on Java 8, too although the conflict with Scala’s reserved word with means backticks are sometimes required.

val friday = ZonedDateTime.now(ZoneId.of("Europe/London")).`with`(TemporalAdjusters.previousOrSame(DayOfWeek.FRIDAY)).truncatedTo(ChronoUnit.MINUTES)

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *