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 obtains 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.example.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          = Mon Feb 01 11:09:55 WITA 2016
java.time.LocalDate     = 2016-02-01
java.time.LocalTime     = 11:09:55.746
java.time.LocalDateTime = 2016-02-01T11:09:55.746
java.util.Date          = Mon Feb 01 11:09:55 WITA 2016

java.util.Calendar      = java.util.GregorianCalendar[time=1454296195871,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Makassar",offset=28800000,dstSavings=0,useDaylight=false,transitions=5,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2016,MONTH=1,WEEK_OF_YEAR=6,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=32,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=9,SECOND=55,MILLISECOND=871,ZONE_OFFSET=28800000,DST_OFFSET=0]
java.time.LocalDateTime = 2016-02-01T11:09:55.871
java.time.LocalDate     = 2016-02-01
java.time.LocalTime     = 11:09:55.871
java.util.Calendar      = java.util.GregorianCalendar[time=1454296195871,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Makassar",offset=28800000,dstSavings=0,useDaylight=false,transitions=5,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2016,MONTH=1,WEEK_OF_YEAR=5,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=32,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=9,SECOND=55,MILLISECOND=871,ZONE_OFFSET=28800000,DST_OFFSET=0]

How do I get the last day of a month?

package org.kodejava.example.util;

import java.util.Calendar;

public class LastDayOfMonth {
    public static void main(String[] args) {
        // Get a calendar instance
        Calendar calendar = Calendar.getInstance();

        // Get the last date of the current month. To get the last date for a
        // specific month you can set the calendar month using calendar object
        // calendar.set(Calendar.MONTH, theMonth) method.
        int lastDate = calendar.getActualMaximum(Calendar.DATE);

        // Set the calendar date to the last date of the month so then we can
        // get the last day of the month
        calendar.set(Calendar.DATE, lastDate);
        int lastDay = calendar.get(Calendar.DAY_OF_WEEK);

        // Print the current date and the last date of the month
        System.out.println("Last Date: " + calendar.getTime());

        // The lastDay will be in a value from 1 to 7 where 1 = monday and 7 =
        // saturday respectively.
        System.out.println("Last Day : " + lastDay);
    }
}

How do I get the last date of a month?

You want to know what is the last date for a current month. The code below show you how to get it.

package org.kodejava.example.util;

import java.util.Calendar;

public class LastDateOfMonth {
    public static void main(String[] args) {
        // Get a calendar instance
        Calendar calendar = Calendar.getInstance();

        // Get the last date of the current month. To get the last date for 
        // a specific month you can set the calendar month using calendar 
        // object calendar.set(Calendar.MONTH, theMonth) method.
        int lastDate = calendar.getActualMaximum(Calendar.DATE);

        // Print the current date and the last date of the month
        System.out.println("Date     : " + calendar.getTime());
        System.out.println("Last Date: " + lastDate);
    }
}

How do I convert day of the year to date?

package org.kodejava.example.util;

import java.util.Calendar;

public class DayOfYearToDate {
    public static void main(String[] args) {
        // In the example we want to get the date value of the specified
        // day of the year. Using the calendar object we can define our
        // calendar for a specific day of the year.

        int dayOfYear = 112;
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);

        System.out.println("Day of year " + dayOfYear + " = "
                + calendar.getTime());

        // If you want to get the date for a specific day of year and for
        // a specific year, you can also pass the year information to the
        // calendar object.

        int year = 2004;
        calendar.set(Calendar.YEAR, year);
        System.out.println("Day of year " + dayOfYear + " in year " + year
                + " = " + calendar.getTime());
    }
}

And here is an example result of the code above:

Day of year 112 = Sun Apr 22 16:53:03 GMT+07:00 2007
Day of year 112 in year 2004 = Wed Apr 21 16:53:03 GMT+07:00 2004

How do I convert day-of-year to day-of-month?

package org.kodejava.example.util;

import java.util.Calendar;

public class DayYearToDayMonth {
    public static void main(String[] args) {
        // Create an instance of calendar for the year 2007 and set the
        // day to the 180 day of the year.
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 2007);
        cal.set(Calendar.DAY_OF_YEAR, 180);

        // Print the date of the calendar.
        System.out.println("Calendar date is: " + cal.getTime());

        // To know what day in month of the calendar we can obtain the
        // value by calling Calendar's instance get() method and pass
        // the Calendar.DAY_OF_MONTH field.
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

        // Print which month day is it in number.
        System.out.println("Calendar day of month: " + dayOfMonth);

        // To know what day in week of the calendar we can obtain the
        // value by calling Calendar's instance get() method and pass
        // the Calendar.DAY_OF_WEEK field.
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

        // Print which week day is it in number.
        System.out.println("Calendar day of week: " + dayOfWeek);
    }
}

The result of our above example is.

Calendar date is: Fri Jun 29 18:24:07 ICT 2007
Calendar day of month: 29
Calendar day of week: 6

How do I check if a year is a leap year?

package org.kodejava.example.util;

import java.util.GregorianCalendar;

public class LeapYearExample {
    public static void main(String[] args) {
        // Here we show how to know if a specified year is a leap year or 
        // not. The GregorianCalendar object provide a convenient method 
        // to do this. The method is GregorianCalendar.isLeapYear().

        // First, let's obtain an instance of GregorianCalendar.
        GregorianCalendar cal = new GregorianCalendar();

        // The isLeapYear(int year) method will return true for leap 
        // year and otherwise return false. In this example the message 
        // will be printed as 2004 is a leap year.
        if (cal.isLeapYear(2004)) {
            System.out.println("The year 2004 is a leap year!");
        }
    }
}

The result of our code is:

The year 2004 is a leap year!

How do I calculate difference in days between two dates?

In the following example we are going to calculate the differences between two dates. First, we will need to convert the date into the corresponding value in milliseconds and then do the math so we can get the difference in days, hours, minutes, etc.

For example to get the difference in day we will need to divide the difference in milliseconds with (24 * 60 * 60 * 1000).

package org.kodejava.example.util;

import java.util.Calendar;

public class DateDifferenceExample {
    public static void main(String[] args) {
        // Creates two calendars instances
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        // Set the date for both of the calendar instance
        cal1.set(2006, Calendar.DECEMBER, 30);
        cal2.set(2007, Calendar.MAY, 3);

        // Get the represented date in milliseconds
        long millis1 = cal1.getTimeInMillis();
        long millis2 = cal2.getTimeInMillis();

        // Calculate difference in milliseconds
        long diff = millis2 - millis1;

        // Calculate difference in seconds
        long diffSeconds = diff / 1000;

        // Calculate difference in minutes
        long diffMinutes = diff / (60 * 1000);

        // Calculate difference in hours
        long diffHours = diff / (60 * 60 * 1000);

        // Calculate difference in days
        long diffDays = diff / (24 * 60 * 60 * 1000);

        System.out.println("In milliseconds: " + diff + " milliseconds.");
        System.out.println("In seconds: " + diffSeconds + " seconds.");
        System.out.println("In minutes: " + diffMinutes + " minutes.");
        System.out.println("In hours: " + diffHours + " hours.");
        System.out.println("In days: " + diffDays + " days.");
    }
}

Here is the result:

In milliseconds: 10713600000 milliseconds.
In seconds: 10713600 seconds.
In minutes: 178560 minutes.
In hours: 2976 hours.
In days: 124 days.

The better way to get number of days between two dates is to use the Joda Time API. In the following example you can see how to calculate date difference using Joda Time: How do I get number of days between two dates in Joda Time?.

How do I convert Date to String?

package org.kodejava.example.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateToString {
    public static void main(String[] args) {
        // Create an instance of SimpleDateFormat used for formatting 
        // the string representation of date (month/day/year)
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");

        // Get the date today using Calendar object.
        Date today = Calendar.getInstance().getTime();        
        // Using DateFormat format method we can create a string 
        // representation of a date with the defined format.
        String reportDate = df.format(today);

        // Print what date is today!
        System.out.println("Report Date: " + reportDate);
    }
}

How do I get day of week?

In this example we want to create a calendar / date from year and day of the year, because that’s all we have. Next we will find what is the day of week of the calendar object is. Let’s see the example below.

package org.kodejava.example.util;

import java.util.Calendar;

public class DayOfYearToDayOfWeekExample {
    public static void main(String[] args) {
        // Create a calendar with year and day of year.
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 2007);
        calendar.set(Calendar.DAY_OF_YEAR, 180);

        // See the full information of the calendar object.
        System.out.println(calendar.getTime().toString());

        // Get the weekday and print it
        int weekday = calendar.get(Calendar.DAY_OF_WEEK);
        System.out.println("Weekday: " + weekday);
    }
}

Below is the result of our program.

Fri Jun 29 17:16:22 ICT 2007
Weekday: 6

How do I get number of days in a month?

Let say you want to know the number of days in a month or we can say it as the last date of a month. The example below shows you how to obtain the number of days or the date.

package org.kodejava.example.util;

import java.util.Calendar;

public class MonthDaysExample {
    public static void main(String[] args) {
        // First get an instance of calendar object.
        Calendar calendar = Calendar.getInstance();

        // We'll set the date of the calendar to the following
        // date. We can use constant variable in the calendar
        // for months value (JANUARY - DECEMBER). Be informed that
        // month in Java started from 0 instead of 1.
        int year = 2007;
        int month = Calendar.FEBRUARY;
        int date = 1;
        // We have a new date of 2007-02-01
        calendar.set(year, month, date);

        // Here we get the maximum days for the date specified
        // in the calendar. In this case we want to get the number
        // of days for february 2007
        int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        System.out.println("Max Day: " + maxDay);

        // Here we want to see what is the days for february on
        // a leap year.
        calendar.set(2004, Calendar.FEBRUARY, 1);
        maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        System.out.println("Max Day: " + maxDay);
    }
}

If you are on JDK8 you can use the new Date Time API to get the number of days in a month. Here an example that show you how to do it: How do I get the length of month represented by a date object?.