Java 8: new Date API

5 04 2014

Continuing Java 8 goodies, here comes the new Date API! Does it mean that one no longer will need to use Joda Time? Not sure, but surely there is an improvement over Date API in earlier Java versions. Calculating difference between two dates was a nightmare…

Creating new date objects
Date parsing from string in local format or defining new date with variables is more intuitive. This will create new LocalDate object pointing to 5th of February 1987:

LocalDate dateFromString = LocalDate.parse("1987-02-05");
LocalDate dateFromVariables = LocalDate.of(1987, 2, 5);

Adding to and subtracting from dates
To specified LocalDate you can easily add or subtract time units. There are convenient LocalDate instance public methods to do it. Basically to add two weeks to the date, you simply write:

LocalDate weekAfter = dateFromString.plusWeeks(1);

Methods you can use to add or substract:
– plusDays(int), minusDays(int)
– plusWeeks(int), minusWeeks(int)
– plusMonths(int), minusMonths(int)

You can also use generic method plus(int, ChronoUnit) that allows to add number of units to date. For example to add one week with a plus() method you write:

LocalDate weekAfterUnit =, ChronoUnit.WEEKS);

Calculating difference between two dates
It’s not a nightmare anymore! With a Period class you can calculate how many days, months or years are between two dates. Just use until() method. To calculate difference between today and particular date, do the following:

LocalDate birthDate = LocalDate.parse("1987-02-05");
LocalDate today =;
Period period = birthDate.until(today);
System.out.println("Years passed: " + period.getYears());

you can also use getMonths() and getDays() methods. To determine whether the date is before or after another date, use the isNegative() method on a Period object.

Did I help you?
I manage this blog and share my knowledge for free, sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!



Give Your feedback:

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: