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.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(2020, 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(2021, 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 2020. 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 month’s length for the year of 2021 from January to December.

And here are the result of our code snippet above:

2021-11-16: 30

2020-02: 29

2021-01: 31
2021-02: 28
2021-03: 31
2021-04: 30
2021-05: 31
2021-06: 30
2021-07: 31
2021-08: 31
2021-09: 30
2021-10: 31
2021-11: 30
2021-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 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.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(2020, 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(2020);
        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 2021, leap year = false
Year 2020, leap year = true
Year 2021, leap year = false
Year 2020, leap year = true

How do I parse a string into date and time?

In this code snippet you will learn how to parse a string into an instance of LocalDate, LocalTime and LocalDateTime. All of these classes provide a parse() method that accept an argument of string that represent a valid date and time information and convert it into the corresponding object.

If the string passed into the parse() method is not representing a valid date or time information this method throws a RuntimeException of type DateTimeParseException exception. If you want to handle this exception then you should wrap your code inside a try-catch block.

Let’s see the code snippet below as an example:

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeParseException;

public class DateTimeParseDemo {
    public static void main(String[] args) {

        // Parse string "2021-09-12" into LocalDate instance.
        LocalDate date = LocalDate.parse("2021-09-12");

        // Parse string "17:51:15: into LocalTime instance.
        LocalTime time = LocalTime.parse("17:51:15");

        // Parse string "2021-09-12T17:51:15" into LocalDateTime instance.
        LocalDateTime dateTime = LocalDateTime.parse("2021-09-12T17:51:15");

        System.out.println("date     = " + date);
        System.out.println("time     = " + time);
        System.out.println("dateTime = " + dateTime);

        try {
            // When the string cannot be parsed, a RuntimeException of type
            // DateTimeParseException will be thrown.
            LocalDate date1 = LocalDate.parse("2021-02-31");
            System.out.println("date1     = " + date1);
        } catch (DateTimeParseException e) {
            e.printStackTrace();
        }
    }
}

Running this code snippet will produce the following result:

date     = 2021-09-12
time     = 17:51:15
dateTime = 2021-09-12T17:51:15
java.time.format.DateTimeParseException: Text '2021-02-31' could not be parsed: Invalid date 'FEBRUARY 31'
    at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2023)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1958)
    at java.base/java.time.LocalDate.parse(LocalDate.java:430)
    at java.base/java.time.LocalDate.parse(LocalDate.java:415)
    at org.kodejava.datetime.DateTimeParseDemo.main(DateTimeParseDemo.java:27)
Caused by: java.time.DateTimeException: Invalid date 'FEBRUARY 31'
    at java.base/java.time.LocalDate.create(LocalDate.java:461)
    at java.base/java.time.LocalDate.of(LocalDate.java:273)
    at java.base/java.time.chrono.IsoChronology.resolveYMD(IsoChronology.java:654)
    at java.base/java.time.chrono.IsoChronology.resolveYMD(IsoChronology.java:126)
    at java.base/java.time.chrono.AbstractChronology.resolveDate(AbstractChronology.java:442)
    at java.base/java.time.chrono.IsoChronology.resolveDate(IsoChronology.java:586)
    at java.base/java.time.chrono.IsoChronology.resolveDate(IsoChronology.java:126)
    at java.base/java.time.format.Parsed.resolveDateFields(Parsed.java:365)
    at java.base/java.time.format.Parsed.resolveFields(Parsed.java:272)
    at java.base/java.time.format.Parsed.resolve(Parsed.java:259)
    at java.base/java.time.format.DateTimeParseContext.toResolved(DateTimeParseContext.java:331)
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2058)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1954)
    ... 3 more

As we can see from the output above, parsing a text string of "2021-02-31" give us a DateTimeParseException because the 31st of February is not a valid date.

How do I use java.time.LocalDateTime class?

The java.time.LocalDateTime class represents information of both date and time without time-zone. We can create LocalDateTime using the available static factory method such as the of() method or by combining an instance of LocalDate and LocalTime.

The following code snippet will show you both ways. First we begin with using the of() method where we can pass arguments such as the year, month, day, hour, minute and second. On the following line we also use the of() method but this time we pass an instance of LocalDate and LocalTime as the arguments.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;

public class LocalDateTimeDemo {
    public static void main(String[] args) {
        // Creates an instance of LocalDateTime using of()
        // static factory method with full date and time arguments.
        LocalDateTime dateTime =
                LocalDateTime.of(2021, Month.SEPTEMBER, 11, 16, 15, 15);
        System.out.println("dateTime  = " + dateTime);

        // Combines LocalDate and LocalTime to creates a new
        // instance of LocalDateTime.
        LocalDate date = LocalDate.now();
        LocalTime time = LocalTime.now();
        LocalDateTime dateTime2 = LocalDateTime.of(date, time);
        System.out.println("dateTime2 = " + dateTime2);

        // Creates LocalDateTime from LocateDate with time using
        // atTime() method.
        LocalDateTime dateTime3 = date.atTime(16, 15, 15);
        LocalDateTime dateTime4 = date.atTime(time);
        System.out.println("dateTime3 = " + dateTime3);
        System.out.println("dateTime4 = " + dateTime4);

        // Creates LocalDateTime from LocalTime with date using
        // atDate() method.
        LocalDateTime dateTime5 = time.atDate(date);
        System.out.println("dateTime5 = " + dateTime5);

        // Obtains LocalDate and LocalTime from LocalDateTime using
        // toLocalDate() and toLocalTime() methods.
        LocalDate date1 = dateTime5.toLocalDate();
        LocalTime time1 = dateTime5.toLocalTime();
        System.out.println("date1 = " + date1);
        System.out.println("time1 = " + time1);
    }
}

We can also create an instance of LocalDateTime by using the LocalDate‘s atTime() method or LocalTime‘s atDate() method as seen in the code snippet above.

On the very end of the code snippet you can see how to obtain a LocalDate or LocalTime information from an instance of LocalDateTime using the toLocalDate() and toLocalTime() method.

Running this code snippet will give you the following result:

dateTime  = 2021-09-11T16:15:15
dateTime2 = 2021-11-16T07:06:36.460459800
dateTime3 = 2021-11-16T16:15:15
dateTime4 = 2021-11-16T07:06:36.460459800
dateTime5 = 2021-11-16T07:06:36.460459800
date1 = 2021-11-16
time1 = 07:06:36.460459800

How do I use java.time.LocalTime class?

An instance of LocalTime class represent information about time. It doesn’t contain information about date. To create an instance of this class we can use the of() static factory method. There are two types of this method. The first one accept two arguments, hour and minute. The second type also accept the second as the arguments.

The code snippet below show you how to create an instance of LocalTime and how to obtain its values.

package org.kodejava.datetime;

import java.time.LocalTime;

public class LocalTimeDemo {
    public static void main(String[] args) {
        LocalTime time = LocalTime.of(15, 5, 30);

        int hour = time.getHour();
        int minute = time.getMinute();
        int second = time.getSecond();

        System.out.println("hour = " + hour);
        System.out.println("minute = " + minute);
        System.out.println("second = " + second);
    }
}

To get the values from the LocalTime object we can use the getHour(), getMinute() and getSecond() methods to get hour, minute and second respectively.

Running this snippet result the following output:

hour = 15
minute = 5
second = 30

You can also use the get() method to read values represented by the LocalTime object. We call this method with the temporal field that we want to read. The following code snippet will give you the same result as the previous code, only this time we use the get() method.

int hour = time.get(ChronoField.HOUR_OF_DAY);       
int minute = time.get(ChronoField.MINUTE_OF_HOUR);  
int second = time.get(ChronoField.SECOND_OF_MINUTE);

System.out.println("hour   = " + hour);             
System.out.println("minute = " + minute);           
System.out.println("second = " + second);