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

How do I parse a text string into date and time?

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

If the text 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.example.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 "2014-09-12" into LocalDate instance.
        LocalDate date = LocalDate.parse("2014-09-12");

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

        // Parse string "2014-09-12T17:51:15" into LocalDateTime instance.
        LocalDateTime dateTime = LocalDateTime.parse("2014-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 parse a RuntimeException of type
            // DateTimeParseException will be thrown.
            LocalDate date1 = LocalDate.parse("2014-02-31");
            System.out.println("date1     = " + date1);
        } catch (DateTimeParseException e) {
            e.printStackTrace();
        }
    }
}

Running this code snippet will produce the following result:

date     = 2014-09-12
time     = 17:51:15
dateTime = 2014-09-12T17:51:15
java.time.format.DateTimeParseException: Text '2014-02-31' could not be parsed: Invalid date 'FEBRUARY 31'
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853)
    at java.time.LocalDate.parse(LocalDate.java:400)
    at java.time.LocalDate.parse(LocalDate.java:385)
    at org.kodejava.example.datetime.DateTimeParseDemo.main(DateTimeParseDemo.java:35)
Caused by: java.time.DateTimeException: Invalid date 'FEBRUARY 31'
    at java.time.LocalDate.create(LocalDate.java:431)
    at java.time.LocalDate.of(LocalDate.java:269)
    at java.time.chrono.IsoChronology.resolveYMD(IsoChronology.java:560)
    at java.time.chrono.IsoChronology.resolveYMD(IsoChronology.java:123)
    at java.time.chrono.AbstractChronology.resolveDate(AbstractChronology.java:472)
    at java.time.chrono.IsoChronology.resolveDate(IsoChronology.java:492)
    at java.time.chrono.IsoChronology.resolveDate(IsoChronology.java:123)
    at java.time.format.Parsed.resolveDateFields(Parsed.java:351)
    at java.time.format.Parsed.resolveFields(Parsed.java:257)
    at java.time.format.Parsed.resolve(Parsed.java:244)
    at java.time.format.DateTimeParseContext.toResolved(DateTimeParseContext.java:331)
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1953)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1849)
    ... 3 more

As we can see from the output above, parsing a text string of "2014-02-31" give us a DateTimeParseException because the 31 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.example.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(2014, 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  = 2014-09-11T16:15:15
dateTime2 = 2014-09-11T16:25:37.891
dateTime3 = 2014-09-11T16:15:15
dateTime4 = 2014-09-11T16:25:37.891
dateTime5 = 2014-09-11T16:25:37.891
date1 = 2014-09-11
time1 = 16:25:37.891

How do I use java.time.LocalTime class?

An instance of LocalTime class represent information about time. It doesn’t contains 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 obtaint its values.

package org.kodejava.example.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);

How do I use java.time.LocalDate class?

JDK8’s LocateDate class is a class that represent information about date. It doesn’t include information about time of day and it also doesn’t have information about time-zone. An instance of this class in an immutable object.

To create an instance of LocateDate class we can use the of() static method factory. We pass arguments such as the year, month and day into this static factory method. The value for month can be an integer between 1 and 12, or you use the value specified by the java.time.Month enum, such as Month.JANUARY.

The code snippet below show you how to use the LocalDate class.

package org.kodejava.example.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;

public class LocalDateDemo {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2014, 9, 7);

        int year = date.getYear();
        Month month = date.getMonth();
        int day = date.getDayOfMonth();

        DayOfWeek dow = date.getDayOfWeek();
        int monthLength = date.lengthOfMonth();
        boolean leapYear = date.isLeapYear();

        System.out.println("Year         = " + year);
        System.out.println("Month        = " + month);
        System.out.println("Day          = " + day);
        System.out.println("Dow          = " + dow);
        System.out.println("Month Length = " + monthLength);
        System.out.println("Leap Year    = " + leapYear);
    }
}

As you can see from the code snippet above, the LocalDate class also provide some methods to get the value from the LocateDate instance. For example you can obtain the year of the date using the getYear() method. To get the month we can use the getMonth() method which will return the Month enum. And to get the day we can use the getDayOfMonth() method.

We can also get information such as the length of the month and check if the year represented by this LocalDate is a leap year. Running the code snippet above will give you the following result:

Year         = 2014
Month        = SEPTEMBER
Day          = 7
Dow          = SUNDAY
Month Length = 30
Leap Year    = false

Beside using the methods shown above to access values from a LocalDate instance we can also use TemporalField as demonstrated in the code snippet below. Here we call the get() method and pass a temporal field that we want to read using the ChronoField enumeration. This enum implements the TemporalField interface.

int year = date.get(ChronoField.YEAR);
int month = date.get(ChronoField.MONTH_OF_YEAR);
int day = date.get(ChronoField.DAY_OF_MONTH);

System.out.println("year  = " + year);
System.out.println("month = " + month);
System.out.println("day   = " + day);

How do I get today’s date and time?

This example show you how to use the new Date and Time API introduced in JDK 8 to get the current date and time. To get today’s date in this new API you can construct an instance of LocalDate, LocalTime or LocalDateTime and call its toString() method.

All of these classes is located under the new java.time package and defined as a final class. Because its constructor declared as a private constructor, this mean you can’t use their constructor to create a new instance. But these classes offer some static factory method to get the value it represents or to create a new instance. For example all of these classes provide a now() method that return the current date, time or date and time information.

Let’s seen a complete code snippet in the TodayDateTime example to demonstrate it.

package org.kodejava.example.datetime;

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

public class TodayDateTime {
    public static void main(String[] args) {
        // Obtains the current date from the system clock in the
        // default time-zone.
        LocalDate currentDate = LocalDate.now();
        System.out.println("currentDate = " + currentDate);

        // Obtains the current time from the system clock in the
        // default time-zone.
        LocalTime currentTime = LocalTime.now();
        System.out.println("currentTime = " + currentTime);

        // Obtains the current date-time from the system clock
        // in the default time-zone.
        LocalDateTime currentDateTime = LocalDateTime.now();
        System.out.println("currentDateTime = " + currentDateTime);
    }
}

Running this program will give you the following result:

currentDate = 2014-09-05
currentTime = 16:39:24.819
currentDateTime = 2014-09-05T16:39:24.820