How do I convert java.util.TimeZone to java.time.ZoneId?

The following code snippet will show you how to convert the old java.util.TimeZone to java.time.ZoneId introduced in Java 8. In the first line of our main() method we get the default timezone using the TimeZone.getDefault() and convert it to ZoneId by calling the toZoneId() method. In the second example we create the TimeZone object by calling the getTimeZone() and pass the string of timezone id. To convert it to ZoneId we call the toZoneId() method.

package org.kodejava.datetime;

import java.time.ZoneId;
import java.util.TimeZone;

public class TimeZoneToZoneId {
    public static void main(String[] args) {
        ZoneId zoneId = TimeZone.getDefault().toZoneId();
        System.out.println("zoneId = " + zoneId);

        TimeZone timeZoneUsPacific = TimeZone.getTimeZone("US/Pacific");
        ZoneId zoneIdUsPacific = timeZoneUsPacific.toZoneId();
        System.out.println("zoneIdUsPacific = " + zoneIdUsPacific);
    }
}

This snippet prints the following output:

zoneId = Asia/Shanghai
zoneIdUsPacific = US/Pacific

To convert the other way around you can do it like the following code snippet. Below we convert the ZoneId to TimeZone by using the TimeZone.getTimeZone() method and pass the ZoneId.systemDefault() which return the system default timezone. Or we can create ZoneId using the ZoneId.of() method and specify the timezone id and then pass it to the getTimeZone() method of the TimeZone class.

package org.kodejava.datetime;

import java.time.ZoneId;
import java.util.TimeZone;

public class ZoneIdToTimeZone {
    public static void main(String[] args) {
        TimeZone timeZone = TimeZone.getTimeZone(ZoneId.systemDefault());
        System.out.println("timeZone = " + timeZone.getDisplayName());

        TimeZone timeZoneUsPacific = TimeZone.getTimeZone(ZoneId.of("US/Pacific"));
        System.out.println("timeZoneUsPacific = " + timeZoneUsPacific.getDisplayName());
    }
}

And here are the output of the code snippet above:

timeZone = China Standard Time
timeZoneUsPacific = Pacific Standard Time

How do I get a list of all TimeZones Ids using Java 8?

To retrieve a list of all available time zones ids we can call the java.time.ZoneId static method getAvailableZoneIds(). This method return a Set of string of all zone ids. The format of the zone id are “{area}/{city}”. You can use these ids of string to create the ZoneId object using the ZoneId.of() static method.

package org.kodejava.datetime;

import java.time.ZoneId;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.Set;

public class GetAllTimeZoneIds {
    public static void main(String[] args) {
        Set<String> zoneIds = ZoneId.getAvailableZoneIds();
        for (String id : zoneIds) {
            ZoneId zoneId = ZoneId.of(id);
            System.out.println("id          = " + id);
            System.out.println("displayName = " +
                    zoneId.getDisplayName(TextStyle.FULL, Locale.US));
        }
    }
}

Here are some zone IDs printed out to the console:

id          = Asia/Aden
displayName = Arabian Time
id          = America/Cuiaba
displayName = Amazon Time
id          = Etc/GMT+9
displayName = GMT-9:00
id          = Etc/GMT+8
displayName = GMT-8:00
id          = Africa/Nairobi
displayName = Eastern Africa Time
...
...
...
id          = Europe/Nicosia
displayName = Eastern European Time
id          = Pacific/Guadalcanal
displayName = Solomon Is. Time
id          = Europe/Athens
displayName = Eastern European Time
id          = US/Pacific
displayName = Pacific Time
id          = Europe/Monaco
displayName = Central European Time

How to convert java.time.LocalDate to java.util.Date?

The following code snippet demonstrate how to convert java.time.LocalDate to java.util.Date and vice versa. In the first part of the code snippet we convert LocalDate to Date and back to LocalDate object. On the second part we convert LocalDateTime to Date and back to LocalDateTime object.

package org.kodejava.datetime;

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

public class LocalDateToDate {
    public static void main(String[] args) {
        // Convert java.time.LocalDate to java.util.Date and back to
        // java.time.LocalDate
        LocalDate localDate = LocalDate.now();
        System.out.println("LocalDate = " + localDate);

        Date date1 = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        System.out.println("Date      = " + date1);

        localDate = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        System.out.println("LocalDate = " + localDate);
        System.out.println();

        // Convert java.time.LocalDateTime to java.util.Date and back to
        // java.time.LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("LocalDateTime = " + localDateTime);

        Date date2 = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        System.out.println("Date          = " + date2);

        localDateTime = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        System.out.println("LocalDateTime = " + localDateTime);
    }
}

The result of the code snippet:

LocalDate = 2021-11-20
Date      = Sat Nov 20 00:00:00 CST 2021
LocalDate = 2021-11-20

LocalDateTime = 2021-11-20T18:25:05.706380200
Date          = Sat Nov 20 18:25:05 CST 2021
LocalDateTime = 2021-11-20T18:25:05.706

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.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       = 2021-11-18
First day of month = 2021-11-01
Last day of month  = 2021-11-30
Next Monday        = 2021-11-22
Last day of year   = 2021-12-31

The table below shows the complete static factory methods 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.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 absoluteAttributeManipulations() {
        System.out.println("LocalDateManipulation.absoluteAttributeManipulations");
        LocalDate date1 = LocalDate.of(2021, 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(2021, 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);
    }

    private static void relativeAttributeManipulations() {
        System.out.println("LocalDateManipulation.relativeAttributeManipulations");
        LocalDate date1 = LocalDate.of(2021, 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(2021, 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);

    }
}

The results of this code snippet are:

LocalDateManipulation.absoluteAttributeManipulations
of(2021, Month.JANUARY, 1)                 => 2021-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(2021, Month.AUGUST, 17)        => 2021-08-17
date1.minusYears(70)              => 1951-08-17
date1.plusMonths(10)              => 1952-06-17
date3.minusDays(15)               => 1952-06-02
date4.plusWeeks(52)               => 1953-06-01
date5.minus(52, ChronoUnit.WEEKS) => 1952-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 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 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

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 use letters pattern 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.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: 2021-11-16T07:51:16.1247212
Time: November 16, 2021 07:51 AM
Time: 16 nov. 2021 07:51:16