How do I convert between old Date and Calendar object with the new Java 8 Date Time?

In this example we will learn how to convert the old java.util.Date and java.util.Calendar objects to the new Date Time introduced in Java 8. The first method in the code snippet below dateToNewDate() show conversion of java.util.Date while the calendarToNewDate() show the conversion of java.util.Calendar.

The java.util.Date and java.util.Calendar provide a toInstant() method to convert the objects to the new Date Time API class of the java.time.Instant. To convert the old date into the Java 8 LocalDate, LocalTime and LocalDateTime we first can create an instance of ZonedDateTime using the atZone() method of the Instant class.

ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());

From an instance of ZonedDateTime class we can call the toLocalDate(), toLocalTime() and toLocalDateTime() to get instance of LocalDate, LocalTime and LocalDateTime.

To convert back from the new Java 8 date to the old java.util.Date we can use the Date.from() static factory method and passing and instance of java.time.Instant that we can obtain by calling the following code.

Instant instant1 = dateTime.atZone(ZoneId.systemDefault()).toInstant();
Date now1 = Date.from(instant1);

Here are the complete code snippet to convert java.util.Date to the new Java 8 Date Time.

private static void dateToNewDate() {
    Date now = new Date();
    Instant instant = now.toInstant();

    ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());

    LocalDate date = zonedDateTime.toLocalDate();
    LocalTime time = zonedDateTime.toLocalTime();
    LocalDateTime dateTime = zonedDateTime.toLocalDateTime();

    Instant instant1 = dateTime.atZone(ZoneId.systemDefault()).toInstant();
    Date now1 = Date.from(instant1);

    System.out.println("java.util.Date          = " + now);
    System.out.println("java.time.LocalDate     = " + date);
    System.out.println("java.time.LocalTime     = " + time);
    System.out.println("java.time.LocalDateTime = " + dateTime);
    System.out.println("java.util.Date          = " + now1);
    System.out.println();
}

The steps for converting from the java.util.Calendar to the new Java 8 date can be seen in the code snippet below. As with java.util.Date the Calendar class provide toInstant() method to convert the calendar to java.time.Instant object.

Using the LocalDateTime.ofInstant() method we can create a LocalDateTime object from the instant object. By having the LocalDateTime object we can then get an instance of LocalDate and LocalTime by calling the toLocalDate() and toLocalTime() method.

Finally, to convert back to java.util.Calendar we can use the GregorianCalendar.from() static factory method which require an instance of ZonedDateTime to be passed as a parameter. To get an instance of ZonedDateTime we can call LocalDateTime.atZone() method. You can see the complete code in the code snippet below.

private static void calendarToNewDate() {
    Calendar now = Calendar.getInstance();

    LocalDateTime dateTime = LocalDateTime.ofInstant(now.toInstant(),
            ZoneId.systemDefault());

    LocalDate date = dateTime.toLocalDate();
    LocalTime time = dateTime.toLocalTime();

    ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.systemDefault());
    Calendar now1 = GregorianCalendar.from(zonedDateTime);

    System.out.println("java.util.Calendar      = " + now);
    System.out.println("java.time.LocalDateTime = " + dateTime);
    System.out.println("java.time.LocalDate     = " + date);
    System.out.println("java.time.LocalTime     = " + time);
    System.out.println("java.util.Calendar      = " + now1);
}

Below is the main Java class to run the code snippet. You must place the above methods inside this class to run the code snippet.

package org.kodejava.datetime;

import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class LegacyDateCalendarToNewDateExample {
    public static void main(String[] args) {
        dateToNewDate();
        calendarToNewDate();
    }
}

Here are the result of the code snippet above. The first group is conversion the java.util.Date to the new Date Time API. The second group is conversion from the java.util.Calendar to the new Date Time API.

java.util.Date          = Tue Nov 16 08:44:51 CST 2021
java.time.LocalDate     = 2021-11-16
java.time.LocalTime     = 08:44:51.031
java.time.LocalDateTime = 2021-11-16T08:44:51.031
java.util.Date          = Tue Nov 16 08:44:51 CST 2021

java.util.Calendar      = java.util.GregorianCalendar[time=1637023491089,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2021,MONTH=10,WEEK_OF_YEAR=47,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=320,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=44,SECOND=51,MILLISECOND=89,ZONE_OFFSET=28800000,DST_OFFSET=0]
java.time.LocalDateTime = 2021-11-16T08:44:51.089
java.time.LocalDate     = 2021-11-16
java.time.LocalTime     = 08:44:51.089
java.util.Calendar      = java.util.GregorianCalendar[time=1637023491089,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2021,MONTH=10,WEEK_OF_YEAR=46,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=320,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=44,SECOND=51,MILLISECOND=89,ZONE_OFFSET=28800000,DST_OFFSET=0]

How do I get the date of the first particular day after a specific date?

In this example we will learn how to get the date of the first particular day that fall after a specific date. In the code snippet below we will find the first Friday that fall after the new year of 2016. First let’s create a LocalDate object that represent the new year of 2016. We can use LocalDate.of() factory method to create the date object.

To get the first occurrence of a specific day-of-week from a date we create a TemporalAdjuster using the TemporalAdjusters.next() method and pass the day-of-week, in this case we pass DayOfWeek.FRIDAY.

After that we create another LocalDate that will hold the next Friday date. The get the date for the next Friday we call newYear.with() method and pass the TemporalAdjuster that we have created earlier.

Now, let’s try the code snippet below.

package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;

public class GetFirstDayAfterDate {
    public static void main(String[] args) {
        // Obtains the current date.
        LocalDate newYear = LocalDate.of(2021, Month.JANUARY, 1);
        System.out.println("New Year = " + newYear);

        // Gets the next Friday.
        TemporalAdjuster nextFriday = TemporalAdjusters.next(DayOfWeek.FRIDAY);
        LocalDate nextFridayDate = newYear.with(nextFriday);
        System.out.printf("The first Friday after the new year of %s is %s%n",
                newYear, nextFridayDate);
    }
}

The code snippet will print out the following result:

New Year = 2021-01-01
The first Friday after the new year of 2021-01-01 is 2021-01-08

How do I add or subtract date in Java 8?

The new Java 8 java.time.LocalDate class provide a plus() and minus() methods to add or subtract an amount of period to or from the LocalDate object.

The period is represented using the java.time.Period class. To create an instance of Period we can use the of(), ofDays(), ofWeeks(), ofMonths() and ofYears() methods.

Let’s see an example using the plus() and minus() method of LocalDate class to add and subtract in the code snippet below:

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.Period;

public class DateAddSubtract {
    public static void main(String[] args) {
        // Create periods in days, weeks, months and years.
        Period p1 = Period.ofDays(7);
        Period p2 = Period.ofWeeks(2);
        Period p3 = Period.ofMonths(1);
        Period p4 = Period.ofYears(1);
        Period p5 = Period.of(1, 1, 7);

        // Obtains current date and add some period to the current date using 
        // the plus() method.
        LocalDate now = LocalDate.now();
        LocalDate date1 = now.plus(p1);
        LocalDate date2 = now.plus(p2);
        LocalDate date3 = now.plus(p3);
        LocalDate date4 = now.plus(p4);
        LocalDate date5 = now.plus(p5);

        // Print out the result of adding some period to the current date.
        System.out.printf("Add some period to the date: %s%n", now);
        System.out.printf("Plus %7s = %s%n", p1, date1);
        System.out.printf("Plus %7s = %s%n", p2, date2);
        System.out.printf("Plus %7s = %s%n", p3, date3);
        System.out.printf("Plus %7s = %s%n", p4, date4);
        System.out.printf("Plus %7s = %s%n%n", p5, date5);

        // Subtract some period from the date using the minus() method.
        System.out.printf("Subtract some period from the date: %s%n", now);
        System.out.printf("Minus %7s = %s%n", p1, now.minus(p1));
        System.out.printf("Minus %7s = %s%n", p2, now.minus(p2));
        System.out.printf("Minus %7s = %s%n", p3, now.minus(p3));
        System.out.printf("Minus %7s = %s%n", p4, now.minus(p4));
        System.out.printf("Minus %7s = %s%n%n", p5, now.minus(p5));
    }
}

And here are the result of the code snippet above:

Add some period to the date: 2021-11-16
Plus     P7D = 2021-11-23
Plus    P14D = 2021-11-30
Plus     P1M = 2021-12-16
Plus     P1Y = 2022-11-16
Plus P1Y1M7D = 2022-12-23

Subtract some period from the date: 2021-11-16
Minus     P7D = 2021-11-09
Minus    P14D = 2021-11-02
Minus     P1M = 2021-10-16
Minus     P1Y = 2020-11-16
Minus P1Y1M7D = 2020-10-09

How do I calculate difference between two dates?

In this example you’ll learn how to use the java.time.Period class (from Java 8) to calculate difference between two dates. Using Period.between() method will give us difference between two dates in years, months and days period.

Beside using the Period class, we also use the ChronoUnit enum to calculate difference between two dates. We use the ChronoUnit.YEARS, ChronoUnit.MONTHS and ChronoUnit.DAYS and call the between() method to get the difference between two dates in years, months and days.

Let’s see an example below.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class DateDifference {
    public static void main(String[] args) {
        LocalDate birthDate = LocalDate.of(1995, Month.AUGUST, 17);
        LocalDate now = LocalDate.now();

        // Obtains a period consisting of the number of years, months and days
        // between two dates.
        Period age = Period.between(birthDate, now);
        System.out.printf("You are now %d years, %d months and %d days old.%n",
                age.getYears(), age.getMonths(), age.getDays());

        // Using ChronoUnit to calculate difference in years, months and days
        // between two dates.
        long years = ChronoUnit.YEARS.between(birthDate, now);
        long months = ChronoUnit.MONTHS.between(birthDate, now);
        long days = ChronoUnit.DAYS.between(birthDate, now);

        System.out.println("Diff in years  = " + years);
        System.out.println("Diff in months = " + months);
        System.out.println("Diff in days   = " + days);
    }
}

The result of our code snippet above are:

You are now 26 years, 2 months and 30 days old.
Diff in years  = 26
Diff in months = 314
Diff in days   = 9588

How do I use the java.time.DayOfWeek enum?

The java.time.DayOfWeek enums in Java 8 Date-Time API describes the days of the week. The enum has constants value from DayOfWeek.MONDAY through DayOfWeek.SUNDAY. These enums also have their integer values where 1 is equal to MONDAY and 7 is equal to SUNDAY.

In the code snippet below you can see a couple usage of the DayOfWeek enums. We start by getting all the enum values using the values() method that return an array of DayOfWeek. We iterate this array and print out the enum value and its corresponding integer value.

// Get DayOfWeek enums value
DayOfWeek[] dayOfWeeks = DayOfWeek.values();
for (int i = 0; i < dayOfWeeks.length; i++) {
    DayOfWeek dayOfWeek = dayOfWeeks[i];
    System.out.println("dayOfWeek[" + i + "] = " + dayOfWeek + "; value = " +
            dayOfWeek.getValue());
}

To create a DayOfWeek object we can use the of(int) factory method. We pass an integer value of this method. For example giving 1 will give us the DayOfWeek.MONDAY. We can also utilize enum valueOf(String) method to create enum from string value.

// Get DayOfWeek from int value
DayOfWeek dayOfWeek = DayOfWeek.of(1);
System.out.println("dayOfWeek = " + dayOfWeek);

// Get DayOfWeek from string value
dayOfWeek = DayOfWeek.valueOf("SATURDAY");
System.out.println("dayOfWeek = " + dayOfWeek);

To get the DayOfWeek from a date-time object we can use the getDayOfWeek() method. Below we get the day of week from a LocalDate object.

// Get DayOfWeek of a date object
LocalDate date = LocalDate.now();
DayOfWeek dow = date.getDayOfWeek();

System.out.println("Date  = " + date);
System.out.println("Dow   = " + dow + "; value = " + dow.getValue());

We can also get the day of week for a specific locale. To do this we can use the DayOfWeek.getDisplayName(TextStyle, Locale) method. The TextStyle can be of value TextStyle.FULL, TextStyle.SHORT, TextStyle.NARROW which will give us the full, short, and narrow version of the display name. The example below get the display name for Indonesian and German version.

// Get DayOfWeek display name in different locale.
Locale locale = new Locale("id", "ID");
String indonesian = dow.getDisplayName(TextStyle.SHORT, locale);
System.out.println("ID = " + indonesian);

String germany = dow.getDisplayName(TextStyle.FULL, Locale.GERMANY);
System.out.println("DE = " + germany);

There is also a plus(long) method that can be used to add number of days to a DayOfWeek object. For example adding 4 to MONDAY will give us DayOfWeek.FRIDAY.

// Adding number of days to DayOfWeek enum.
System.out.println("DayOfWeek.MONDAY.plus(4) = " + DayOfWeek.MONDAY.plus(4));

Here is the complete code for the snippets above:

package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.Locale;

public class DayOffWeekExample {
    public static void main(String[] args) {
        // Get DayOfWeek enums value
        DayOfWeek[] dayOfWeeks = DayOfWeek.values();
        for (int i = 0; i < dayOfWeeks.length; i++) {
            DayOfWeek dayOfWeek = dayOfWeeks[i];
            System.out.println("dayOfWeek[" + i + "] = " + dayOfWeek + "; value = " +
                    dayOfWeek.getValue());
        }

        // Get DayOfWeek from int value
        DayOfWeek dayOfWeek = DayOfWeek.of(1);
        System.out.println("dayOfWeek = " + dayOfWeek);

        // Get DayOfWeek from string value
        dayOfWeek = DayOfWeek.valueOf("SATURDAY");
        System.out.println("dayOfWeek = " + dayOfWeek);

        // Get DayOfWeek of a date object
        LocalDate date = LocalDate.now();
        DayOfWeek dow = date.getDayOfWeek();

        System.out.println("Date  = " + date);
        System.out.println("Dow   = " + dow + "; value = " + dow.getValue());

        // Get DayOfWeek display name in different locale.
        Locale locale = new Locale("id", "ID");
        String indonesian = dow.getDisplayName(TextStyle.SHORT, locale);
        System.out.println("ID = " + indonesian);

        String germany = dow.getDisplayName(TextStyle.FULL, Locale.GERMANY);
        System.out.println("DE = " + germany);

        // Adding number of days to DayOfWeek enum.
        System.out.println("DayOfWeek.MONDAY.plus(4) = " + DayOfWeek.MONDAY.plus(4));
    }
}

And the result of the code above are:

dayOfWeek[0] = MONDAY; value = 1
dayOfWeek[1] = TUESDAY; value = 2
dayOfWeek[2] = WEDNESDAY; value = 3
dayOfWeek[3] = THURSDAY; value = 4
dayOfWeek[4] = FRIDAY; value = 5
dayOfWeek[5] = SATURDAY; value = 6
dayOfWeek[6] = SUNDAY; value = 7
dayOfWeek = MONDAY
dayOfWeek = SATURDAY
Date  = 2021-11-16
Dow   = TUESDAY; value = 2
ID = Sel
DE = Dienstag
DayOfWeek.MONDAY.plus(4) = FRIDAY