Java date and time tutorial

This tutorial explains basics of date and time manipulation in Java 8.

Java 8 comes with great date and time api that makes working with date and time in Java much easier than it was in the previous Java versions.

This tutorial will discuss classes related to localized date and time that does not involve time zones. Working with time zones require much more care than working with localized dates and times, therefore it’s beyond of this basics tutorial scope.

Java Date and Time

Localized dates and times are stored in three classes from java.time package: LocalDate which stores only date, LocalTime which stores only time, and LocalDateTime that stores both date and time. Those classes follow ISO 8601 standard, based on Gregorian calendar. If you need to work with non-Gregorian calendars like Thai Buddhist calendar, see java.chrono package.

All of those classes have private constructors and cannot be instantiated using the new keyword.

Creating date and time

Current date and time

Dates and times are stored in the three earlier mentioned classes: LocalDate, LocalTime, LocalDateTime. To instantiate those classes with the current time (or more precisely, with the system time), use the static now() method belonging to those classes.

LocalDate ld = LocalDate.now();
LocalTime lt = LocalTime.now();
LocalDateTime ldt = LocalDateTime.now();

System.out.println(ld); // -> "2016-03-21"
System.out.println(lt); // -> "23:38:09.958"
System.out.println(ldt); // -> "2016-03-21T23:38:09.958"

All three classes have their own implementation of toString() method that prints date/time in ISO-8601 formats. Note that the formatting will vary from system to system, depending on system locale. My system locale is set to German locale, therefore I get my dates and times in European format. If your system is set to locale that uses different date and time formatting, like United States, you will see different result for the code above. In later part of this tutorial you will learn how to format your dates and times to get the same format on all systems with any locale set.

One important thing to note is the time format. In the code above we can see time result as 23:38:09.958. Don’t get tricked by the 958 part composed from three digits. Those are not milliseconds. Those are nanoseconds that can take up to 9 digits (nanosecond values are in range of 0 to 999,999,999). By default, Java will take away all zeros from the right side, therefore we see .958 instead of .958000000.

Specific dates

To instantiate LocalDate with specific date, use static method of(year, month, day). Nothing will better explain the usage as example code:

// Let us create a date of 21th March 2016
LocalDate ld1 = LocalDate.of(2016, Month.MARCH, 21);
LocalDate ld2 = LocalDate.of(2016, 3, 21);

Both lines of the code do the same thing but using different type for the second argument. In the first argument we pick up a month from the Month enum. The second example uses integer to represent the month. As March is a third month of year, we pass in integer 3.

Specific times

To instantiate LocalTime with specific time, use static method of(hour, minutes) or one of its overloaded versions. Note that Java uses 24 hour system – hour values are in range of 0 to 23.

// Creating time 15:38 (3:38pm)
LocalTime lt1 = LocalTime.of(15, 38);

// Creating time 15:38:22 (hours, minutes, seconds)
LocalTime lt2 = LocalTime.of(15, 38, 22);

// Creating time 15:38:22.293481034 (hours, minutes, seconds, nanoseconds)
LocalTime lt3 = LocalTime.of(15, 38, 22,293481034);

Specific date and time

The LocalDateTime contains both date and time. This classes uses a static method called of with the syntax similar to the LocalDate and LocalTime classes.

// Creating 21th March 2016, 15:38
// params: year, month, day, hour, minutes
LocalDateTime ldt1 = LocalDateTime.of(2016, Month.MARCH, 21, 15, 38); 

// Creating 21th March 2016, 15:38:22
// params: year, month, day, hour, minutes, seconds
LocalDateTime ldt2 = LocalDateTime.of(2016, Month.MARCH, 21, 15, 38, 22);

// Creating 21th March 2016, 15:38:22.293481034
// params: year, month, day, hour, minutes, seconds, nanoseconds
LocalDateTime ldt3 = LocalDateTime.of(2016, Month.MARCH, 21, 15, 38, 22, 293481034);

// You can also use LocalDate and LocalTime objects
// to create a new LocalDateTime object
LocalDate ld = LocalDate.of(2016, Month.MARCH, 21);
LocalTime lt = LocalTime.of(15, 38);
LocalDateTime ldt4 = LocalDateTime(ld, lt);

Manipulating date and time

Thanks to Java 8 we can manipulate date and time in a safe and easy way. If you are going to build a time-travel machine, consider deploying Java 8.

plus and minus methods

You can easily add and subtract units of time from your date and time objects with plus and minus methods.

LocalDate LocalTime
ld.plusYears(1) ld.minusYears(1) lt.plusHours(1) lt.minusHours(1)
ld.plusMonths(1) ld.minusMonths(1) lt.plusMinutes(1) lt.minusHours(1)
ld.plusWeeks(1) ld.minusWeeks(1) lt.plusSeconds(1) lt.minusSeconds(1)
ld.plusDays(1) ld.minusDays(1) lt.plusNanos(1) lt.minusNanos(1)

Note: LocalDateTime contains all methods from the table above

It’s important to remember that date and time classes are immutable. All of the methods above will return a new object with updated date or time, without modifying the object from which the method was called.

Some examples:

LocalDate ld = LocalDate.of(2015, 10, 21);
LocalTime lt = LocalTime.of(19, 28);
LocalDateTime ldt = LocalDateTime.of(ld, lt);

// Move the date 5 days forward and 30 years backward
ld = ld.plusDays(5);
ld = ld.minusYears(30);
System.out.println(ld); // -> 1985-10-26

// Move the time 1 hour and and 32 minutes forward
lt = lt.plusHours(1).plusMinutes(32); // methods can be chained
System.out.println(lt); // -> 21:00

// Do the same as above but on LocalDateTime object
ldt = ldt.plusDays(5)
         .minusYears(30)
         .plusHours(1)
         .plusMinutes(32);
System.out.println(ldt); // -> 1985-10-26T21:00

Reading and displaying date and time

get methods

You can read separate parts of date and time with get methods.

LocalDate LocalTime
method example result method example result
ld.getYear() 2016 lt.getHour() 14
ld.getMonth() Month.MARCH lt.getMinute() 15
ld.getMonthValue() 3 lt.getSecond() 30
ld.getDayOfMonth() 25 lt.getNano() 394837592
ld.getDayOfWeek() DayOfWeek.FRIDAY
ld.getDayOfYear() 85

Note: LocalDateTime contains all methods from the table above

DateTimeFormatter.ofPattern method

The ofPattern method from java.time.format.DateTimeFormatter class allows you to format date and time with your own patterns.

The example code below explains the usage:

LocalDateTime ldt = LocalDateTime.now();
DateTimeFormatter myFormatter = DateTimeFormatter.ofPattern("HH:mm, dd MMM yyyy");

System.out.println( ldt.format(myFormatter) ); // -> 23:46, 26 Mar 2016
// or
System.out.println (myFormatter.format(ldt) ); // -> 23:46, 26 Mar 2016

First we create a pattern with DateTimeFormatter.ofPattern(String pattern) method. Then we use format method from either DateTimeFormatter or LocalDateTime object (LocalDate and LocalTime can be used as well).

Below are tables with most commonly used pattern letter. The full list can be found in DateTimeFormatter documentation.

Date formats
Symbol Meaning Example
d Day 5
dd Day (with leading zero) 05
M Month 1
MM Month (with leading zero) 01
MMM Month name in short form Jan
MMMM Month name in long form January
yy Year, two digits 16
yyyy Year, four digits 2016
E Day of week, 3 letters Sun
EEEE Day of week, full name Sunday
Time formats
Symbol Meaning Example
h Hour in 12h system 5
hh Hour in 12h system (with leading zero) 05
a Displays AM or PM PM
H Hour in 24h system 17
HH Hour in 24h system (with leading zero) 17
m Minutes 3
mm Minutes (with leading zero) 03
s Seconds 8
ss Seconds (with leading zero) 08

Learn more about Java