Java 8 Date & Time API Cheat Sheet

Leave a comment

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 =;
Date now = Date.from(utc.toInstant());

// Convert java.time.ZonedDateTime to milliseconds from Epoch (java.util.Date#getTime)
ZonedDateTime utc =;

// Start of today
ZonedDateTime startOfToday =;

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

// Start of this month
ZonedDateTime startOfMonth =;

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

// 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

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 ="Europe/London")).`with`(TemporalAdjusters.previousOrSame(DayOfWeek.FRIDAY)).truncatedTo(ChronoUnit.MINUTES)



Leave a Reply

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