Get up to 80 % extra points for free! More info:

Lesson 14 - Date and Time in Java - Parsing and comparing

In the previous lesson, Date and Time in Java - Modifying and intervals, we learned to convert between LocalDateTime, LocalDate, and LocalTime, modify the inner value, and introduced time intervals. In today's Java course tutorial, we're going to finish with the topic of date and time. We'll get inner values, parse using custom formats, and compare.

Retrieving the value

We read values using the get*() methods on the instance:

LocalDate halloween = LocalDate.of(2016, Month.OCTOBER, 31);
System.out.println("Year: " + halloween.getYear() + ", month: " + halloween.getMonthValue() + ", day: " + halloween.getDayOfMonth());

The result:

Console application
Year: 2016, month: 10, day: 31

Notice the use of the getMonthValue() to retrieve the month number. In this case, we had to use it because getMonth() would return the value of the enumerated Month type.

Note: If you ever encounter the older Calendar class, beware that months were zero-based back then (January was 0, not 1 like it is now in LocalDate/Local­DateTime).

Parsing date and time

As you may already know, date and time often comes as a String, e.g. from the user through the console, a file or the database. We then create a LocalDateTime from the string value using the parse() method right on the data type as we're used to in Java.

The default parse() method expects dates to be in the "yyyy-mm-dd" format, date and times in the "yyyy-mm-ddThh:mm:ss" format and times in the "hh:mm:ss" format. All of the numbers have to have leading zeros if they're less than 10. The "T" isn't a typo. It's more of a separator for date and time:

LocalDateTime dateTime = LocalDateTime.parse("2016-12-08T10:20:30");
LocalDate date = LocalDate.parse("2016-12-08");
LocalTime time = LocalTime.parse("10:20:30");

System.out.println(dateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)));
System.out.println(date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)));
System.out.println(time.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM)));

The result:

Console application
Dec 8, 2016 10:20:30 AM
Dec 8, 2016
10:20:30 AM

Custom formats

Even more so, we'll need to parse an American date and time or date and time in some other format. The default "T" separator for date and time isn't very user-friendly :)

LocalDateTime dateTime = LocalDateTime.parse("12/08/2016 10:20:30", DateTimeFormatter.ofPattern("M/d/y HH:mm:ss"));
LocalDate date = LocalDate.parse("12/8/2016", DateTimeFormatter.ofPattern("M/d/y"));
LocalTime time = LocalTime.parse("10:20:30", DateTimeFormatter.ofPattern("H:m:ss"));

System.out.println(dateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)));
System.out.println(date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)));
System.out.println(time.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM)));

The result:

Console application
Dec 8, 2016 10:20:30 AM
Dec 8, 2016
10:20:30 AM

Comparing instances

Since Java doesn't support operator overloading, we compare the dates using methods. They all start with is*(), let's go through them:

  • isAfter(date) - Returns whether the instance is after the date/date and time passed through the parameter (whether the value is greater).
  • isBefore(date) - Returns whether the instance is before the date/date and time passed through the parameter (whether the value is lesser).
  • isEqual(date) - Returns whether the instance is set to the same date and/or time as the instance passed through the parameter (whether the value is equal).

Easy enough, right? While on the topic of is*() methods, let's go over the rest of them:

  • isLeapYear() - Returns whether the instance is set to a leap year or not.
  • isSupported(Chro­noUnit) - Returns whether the instance supports a given chrono unit (e.g. LocalDate won't support ChronoUnit.HOURS since it doesn't carry any time information).

Here’s an example of their use:

LocalDate halloween = LocalDate.of(2016, 10, 31);
LocalDate christmas = LocalDate.of(2016, 12, 25);
System.out.println("after: " + halloween.isAfter(christmas));
System.out.println("before: " + halloween.isBefore(christmas));
System.out.println("equals: " + christmas.isEqual(halloween));
System.out.println("equals: " + halloween.isEqual(halloween));
System.out.println("leap: " + halloween.isLeapYear());
System.out.println("leap: " + halloween.withYear(2017).isLeapYear());
System.out.println("supports hours: " + halloween.isSupported(ChronoUnit.HOURS));
System.out.println("supports years: " + halloween.isSupported(ChronoUnit.YEARS));

The result:

Console application
after: false
before: true
equals: false
equals: true
leap: true
leap: false
supports hours: false
supports years: true

Other classes

Aside from LocalDateTime, LocalDate, and LocalTime, you may also encounter several other classes which you may find useful rather for applications which main purpose is date and time manipulation. Don’t worry, you'll get by with LocalDateTime in most applications. However, you should be aware of the existence of the following classes.

Instant

Instant represents a date and time that is not related to the calendar or to daylight saving. It's stored as a number of nanoseconds since 1/1/1970, which gives it a certain point on the UTC (universal time) timeline. The following code will always print the same date and time no matter where you’re located on the planet:

Instant instantNow = Instant.now();
System.out.println(instantNow);

Instant is only aware of universal time, so it'll differ from a particular area’s local time.

OffsetDateTime and ZonedDateTime

Now you know that Instant is used for universal time and LocalDateTime is used for a particular area’s local time. We wouldn't be able to get a point in a timeline from LocalDateTime since it doesn't carry any area information.

Wouldn't it be great if there was a class where date and time would be local and also carry the area information (timezone)? This way, we'd be able to convert between various time zones. Well, that's exactly what the ZonedDateTime class is there for.

You may also encounter the OffsetDateTime class in Java, which is an intermediate structure carrying the timezone offset. However, it comes without full timezone support.

ZoneId

In Java, time zones are represented by the ZoneId class. Here's an example of its use (creating an instance based on a time zone):

ZonedDateTime localDateTime = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println(localDateTime);

The output:

Console application
2016-12-09T04:30:41.597-05:00[America/New_York]

You may now be thinking, that's a lot of classes. I suggest that you treat it rather as information to which you may return to when you need it. There are more classes in Java than in many other programming languages. The best way to become a solid Java programmer is to be patient and develop some endurance to the fact. On the other hand, this is why we’re better paid than others :) We'll get to some more practical programming in the next lesson so as to take a break from the theoretical aspects of it all.

Epochas

To top it all off, we’ll get acquainted with some more LocalDateTime methods.

  • ofEpochSecond() - A static method allowing us to create a LocalDateTime instance from a Linux timestamp which was used to store dates in the past. In returns the number of seconds since 1/1/1970 (the beginning of the Linux epoch), which is a huge number, and we also have to specify the nanoseconds (mostly 0) as well as the timezome (most often ZoneOffset.UTC). The method is also available on LocalDate as ofEpochDay() where it receives the number of days rather than seconds.
  • toEpochSecond() and toEpochDay() - These methods do the exact opposite of the ones mentioned above. They convert the instance to the number of seconds/days since 1970.

That is all for date and time in Java 8. We'll code a practical application in the next lesson, Solved tasks for OOP in Java lesson 12. It'll be an electronic diary.

In the following exercise, Solved tasks for OOP in Java lesson 12, we're gonna practice our knowledge from previous lessons.


 

Previous article
Date and Time in Java - Modifying and intervals
All articles in this section
Object-Oriented Programming in Java
Skip article
(not recommended)
Solved tasks for OOP in Java lesson 12
Article has been written for you by David Capka Hartinger
Avatar
User rating:
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities