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

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