Tools

Category: Date Time

In the previous post, How do I find the difference between two times?, we get the difference between two LocalTime objects in seconds measurement. In this example we will get the difference between two LocalDateTime objects and get the difference between these objects in years, months, days, hours, minutes, seconds and milliseconds.

The following code snippet show you how to find the difference between two time objects represented by LocalTime class. To get the difference between two LocalTime objects we can use the Duration.between() method. This method returns a Duration object, to get the difference in seconds we call the getSeconds() method.

Using the Duration.between() we can also get the difference between two LocalDateTime objects and two Instant object as seen in the diffLocalDateTime() method and diffInstant method in the code snippet above.

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 obtains by calling the following code.

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.

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.

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.

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.

Besides 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.example.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 20 years, 5 months and 5 days old.
Diff in years = 20
Diff in months = 245
Diff in days = 7463

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.

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.

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.

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.

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.

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.

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.