How do I manipulate LocalDate object using TemporalAdjuster?

In the previous example we manipulate the value of LocalDate by adding or subtracting the value of date object by days, months, years using methods like plusMonths() or minusDays(). Or by changing the year or the month of the date object using methods like withYear() or withMonth().

But there are times that we want to manipulate the date object so that we can get the first day of the month or the last day of the month. We want to manipulate the date value to advance the date to the first Monday after the current day or the last the of the year.

To manipulate the date object in this way we can use the with() method and pass a TemporalAdjuster object as an argument. Fortunately, the Date and Time API already provide some commonly used TemporalAdjuster. These TemporalAdjuster are provided as a static factory methods that we can find in the java.time.temporal.TemporalAdjusters class.

The following example is a code snippet to manipulate the date object using TemporalAdjuster / TemporalAdjusters class.

package org.kodejava.example.datetime;

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

public class DateManipulationWithTemporalAdjuster {
    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
        System.out.println("Current date       = " + date);

        LocalDate date1 = date.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("First day of month = " + date1);

        LocalDate date2 = date.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("Last day of month  = " + date2);

        LocalDate date3 = date.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
        System.out.println("Next Monday        = " + date3);

        LocalDate date4 = date.with(TemporalAdjusters.lastDayOfYear());
        System.out.println("Last day of year   = " + date4);
    }
}

The result of the code snippet are:

Current date       = 2016-03-06
First day of month = 2016-03-01
Last day of month  = 2016-03-31
Next Monday        = 2016-03-07
Last day of year   = 2016-12-31

The table below shows the complete of static factory method provided by the TemporalAdjusters class.

Method Name Method Description
dayOfWeekInMonth Returns a new date in the same month with the ordinal day-of-week.
firstDayOfMonth Returns a new date set to the first day of the current month.
firstDayOfNextMonth Returns a new date set to the first day of the next month.
firstDayOfNextYear Returns a new date set to the first day of the next year.
firstDayOfYear Returns a new date set to the first day of the current year.
firstInMonth Returns a new date in the same month with the first matching day-of-week.
lastDayOfMonth Returns a new date set to the last day of the current month.
lastDayOfYear Returns a new date set to the last day of the current year.
lastInMonth Returns a new date in the same month with the last matching day-of-week.
next Returns the next day-of-week adjuster.
nextOrSame Returns the next-or-same day-of-week adjuster.
ofDateAdjuster Returns user-written adjuster.
previous Returns the previous day-of-week adjuster.
previousOrSame Returns the previous-or-same day-of-week adjuster.

How do I manipulate the value of LocalDate object?

In the following example we will learn how to manipulate a LocalDate object. There are many methods available for us to change the value of a LocalDate object. For example we can change the year, month and day of LocalDate object. We can use methods like withYear(), withDayOfMonth(), plusYears(), minusMonths(), etc. All these methods will return a new LocalDate object, the original LocalDate will stay unchanged.

Let’s see the following code example for demonstration on how to manipulate the value of LocalDate object.

package org.kodejava.example.datetime;

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

public class LocalDateManipulation {
    public static void main(String[] args) {
        absoluteAttributeManipulations();
        relativeAttributeManipulations();
    }

    private static void relativeAttributeManipulations() {
        System.out.println("LocalDateManipulation.relativeAttributeManipulations");
        LocalDate date1 = LocalDate.of(2015, Month.AUGUST, 17);
        LocalDate date2 = date1.minusYears(70);
        LocalDate date3 = date2.plusMonths(10);
        LocalDate date4 = date3.minusDays(15);
        LocalDate date5 = date4.plusWeeks(52);
        LocalDate date6 = date5.minus(52, ChronoUnit.WEEKS);

        System.out.println("of(2015, Month.AUGUST, 17)        => " + date1);
        System.out.println("date1.minusYears(70)              => " + date2);
        System.out.println("date1.plusMonths(10)              => " + date3);
        System.out.println("date3.minusDays(15)               => " + date4);
        System.out.println("date4.plusWeeks(52)               => " + date5);
        System.out.println("date5.minus(52, ChronoUnit.WEEKS) => " + date6);

    }

    private static void absoluteAttributeManipulations() {
        System.out.println("LocalDateManipulation.absoluteAttributeManipulations");
        LocalDate date1 = LocalDate.of(2016, Month.JANUARY, 1);
        LocalDate date2 = date1.withYear(2010);
        LocalDate date3 = date2.withMonth(Month.DECEMBER.getValue());
        LocalDate date4 = date3.withDayOfMonth(15);
        LocalDate date5 = date4.with(ChronoField.DAY_OF_YEAR, 100);

        System.out.println("of(2016, Month.JANUARY, 1)                 => " + date1);
        System.out.println("date1.withYear(2010)                       => " + date2);
        System.out.println("date2.withMonth(Month.DECEMBER.getValue()) => " + date3);
        System.out.println("date3.withDayOfMonth(15)                   => " + date4);
        System.out.println("date4.with(ChronoField.DAY_OF_YEAR, 100)   => " + date5);
    }
}

The results of this code snippet are:

LocalDateManipulation.absoluteAttributeManipulations
of(2016, Month.JANUARY, 1)                 => 2016-01-01
date1.withYear(2010)                       => 2010-01-01
date2.withMonth(Month.DECEMBER.getValue()) => 2010-12-01
date3.withDayOfMonth(15)                   => 2010-12-15
date4.with(ChronoField.DAY_OF_YEAR, 100)   => 2010-04-10

LocalDateManipulation.relativeAttributeManipulations
of(2015, Month.AUGUST, 17)        => 2015-08-17
date1.minusYears(70)              => 1945-08-17
date1.plusMonths(10)              => 1946-06-17
date3.minusDays(15)               => 1946-06-02
date4.plusWeeks(52)               => 1947-06-01
date5.minus(52, ChronoUnit.WEEKS) => 1946-06-02

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 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.example.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(2016, 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, nextFriday);
    }
}

The code snippet will print out the following result:

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

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.

Besides 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.example.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 20 years, 5 months and 5 days old.
Diff in years  = 20
Diff in months = 245
Diff in days   = 7463

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 use 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.example.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  = 2015-11-16
Dow   = MONDAY; value = 1
ID = Sen
DE = Montag
DayOfWeek.MONDAY.plus(4) = FRIDAY

How do I format date-time objects in Java 8?

In your Java application you want to format date-time objects using the new date and time API introduced in JDK 8. A solution to this problem is to use the java.time.format.DateTimeFormatter. The DateTimeFormatter class provides formatter for printing and parsing date-time objects.

With this class we can format the date-time objects using a predefined constants, there are many predefined ready to use formats, such as ISO_DATE, ISO_DATE_TIME. You can also using the pattern letters to format the date-time objects, for instance using the dd MMMM yyyy. The formatter can format in localized style, in a long or medium style.

Let’s see an example below:

package org.kodejava.example.datetime;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateTimeFormatterDemo {
    public static void main(String[] args) {
        // Get system current date and time.
        LocalDateTime time = LocalDateTime.now();

        // Get an instance of DateTimeFormatter and print a
        // formatted version of the system current date-time
        // using a predefined formatter.
        DateTimeFormatter format = DateTimeFormatter.ISO_DATE_TIME;
        System.out.printf("Time: %s%n", time.format(format));

        // Create a custom formatter and format the date-time
        // object.
        DateTimeFormatter customFormat = 
                DateTimeFormatter.ofPattern("MMMM d, yyyy hh:mm a");
        System.out.printf("Time: %s%n", time.format(customFormat));

        // Create a custom formatter with locale and format the
        // date-time object.
        DateTimeFormatter localeFormat = 
                DateTimeFormatter.ofPattern("d MMM yyyy HH:mm:ss", 
                    Locale.FRENCH);
        System.out.printf("Time: %s%n", time.format(localeFormat));
    }
}

The results of the code above are:

Time: 2016-02-07T22:57:47.402
Time: February 7, 2016 10:57 PM
Time: 7 févr. 2016 22:57:47

How do I install Oracle Java in Ubuntu Server 14.04?

The easiest way to install Oracle Java (JDK) in Ubuntu is to use the WebUpd8 PPA. A PPA (Personal Package Archive) is a special software repository for uploading source packages to be build and published as an APT repository by Launchpad. This PPA will download the required files from Oracle and install JDK7 / JDK8 / JDK9.

The steps:

  • Login to Ubuntu server.
  • sudo apt-add-repository ppa:webupd8team/java

The apt-add-repository command add the ppa to the current repository. You will be prompted with information message about installation instructions with the detail url. You need to press ENTER key to continue the process to add the repository.

apt-add-repository

apt-add-repository

  • sudo apt-get update

This will update the package list from the repositories and update them to get the latest versions of the packages and their dependencies. It will update all repositories and PPAs.

apt-get update

apt-get update

  • sudo apt-get install oracle-java8-installer

This command will start the installation process, you will be prompted to accept the license agreement. Run sudo apt-get install oracle-java7-installer if you want to install JDK7 instead. This process will take sometime to finish depending on your connection speed. And if everything runs well you’ll get Java installed at the end of this process.

apt-get install oracle-java8-installer

apt-get install oracle-java8-installer

  • java -version

This command return the version of the installed JDK. In this case it should return something like:

java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

The JDK8 will be installed in the /usr/lib/jvm/java-8-oracle directory. If you need to define the JAVA_HOME environment variable then it should directed to this directory.

How do I get the length of month represented by a date object?

The following example show you how to get the length of a month represented by a java.time.LocalDate and a java.time.YearMonth objects. Both of these classes have a method called lengthOfMonth() that returns the length of month in days represented by those date objects.

package org.kodejava.example.datetime;

import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;

public class LengthOfMonth {
    public static void main(String[] args) {
        //
        // Get the length of month of the current date.
        //
        LocalDate date = LocalDate.now();
        System.out.printf("%s: %d%n%n", date, date.lengthOfMonth());

        //
        // Get the length of month of a year-month combination value
        // represented by the YearMonth object.
        //
        YearMonth yearMonth = YearMonth.of(2015, Month.FEBRUARY);
        System.out.printf("%s: %d%n%n", yearMonth, yearMonth.lengthOfMonth());

        //
        // Repeat a process the get the length of a month for one year
        // period.
        //
        for (int month = 1; month <= 12; month++) {
            yearMonth = YearMonth.of(2010, Month.of(month));
            System.out.printf("%s: %d%n", yearMonth, yearMonth.lengthOfMonth());
        }
    }
}    

The main() method above start by showing you how to get the month length of a LocalDate object. First we create a LocalDate object using the LocalDate.now() static factory method which return today’s date. And then we print out the length of month of today’s date on the following line.

The next snippet use the YearMonth class. We begin by creating a YearMonth object that represent the month of February 2015. We created it using the YearMonth.of() static factory method. We then print out the length of month for those year-month combination.

In the last lines of the example we create a for loop to get all months length for the year of 2010 from January to December.

And here are the result of our code snippet above:

2015-07-17: 31

2015-02: 28

2010-01: 31
2010-02: 28
2010-03: 31
2010-04: 30
2010-05: 31
2010-06: 30
2010-07: 31
2010-08: 31
2010-09: 30
2010-10: 31
2010-11: 30
2010-12: 31

How do I know if a given year is a leap year?

The example How do I check if a year is a leap year? use the java.util.Calendar object to determine if a given year is a leap year. That was a the way to do it using the old API before we have the Date and Time API introduced in Java 8.

Now, in the Java 8 API we can check if a given year is a leap year using a couple of ways. We can determine if a given date is in a leap year by calling the isLeapYear() method of the java.time.LocalDate class. While using the java.time.Year class we can check is the given year if a leap year using the isLeap() method.

The following code snippet will show you how to do it:

package org.kodejava.example.datetime;

import java.time.LocalDate;
import java.time.Month;
import java.time.Year;
import java.time.temporal.ChronoField;

public class YearIsLeapExample {
    public static void main(String[] args) {
        //
        // Using the java.time.LocalDate class.
        //
        LocalDate now = LocalDate.now();
        boolean isLeap = now.isLeapYear();
        System.out.printf("Year %d, leap year = %s%n", now.getYear(), isLeap);

        LocalDate date = LocalDate.of(2012, Month.JANUARY, 1);
        isLeap = date.isLeapYear();
        System.out.printf("Year %d, leap year = %s%n", date.getYear(), isLeap);

        //
        // Using the java.time.Year class.
        //
        Year year = Year.now();
        isLeap = year.isLeap();
        System.out.printf("Year %d, leap year = %s%n", year.getValue(), isLeap);

        Year anotherYear = Year.of(2012);
        isLeap = anotherYear.isLeap();
        System.out.printf("Year %d, leap year = %s%n", anotherYear.get(ChronoField.YEAR), isLeap);
    }
}

The code snippet will print out the following result:

Year 2015, leap year = false
Year 2012, leap year = true
Year 2015, leap year = false
Year 2012, leap year = true