About Bill Bejeck

Husband, father of 3, passionate about software development.

What’s new in Java 8 – Date API

With the final release of Java 8 around the corner, one of the new features I’m excited about is the new Date API, a result of the work on JSR 310. While Lambda expressions are certainly the big draw of Java 8, having a better way to work with dates is a decidedly welcome addition. This is a quick post (part 1 of 2 or 3) showing some highlights of the new Date functionality, this time mostly around the LocalDate class.

Creating New Date Objects

Creating a new Date object representing a specific day is as easy as:
 

LocalDate today = LocalDate.parse("2014-02-27");
//or this method
LocalDate bday = LocalDate.of(2014,3,18);

Adding To Dates

As an example of the ease with which we can work with dates in Java 8, consider the case where we need to add either days, months or years to an existing date. There are the methods LocalDate.plusDays,LocalDate.plusWeeks, LocalDate.plusMonths LocalDate.plusYears. There is also a generic LocalDate.plus method where you specify how much to add and the time unit via a TemporalUnit type. Here some examples:

@Test
	public void test_add_to_date() {
	 
	    LocalDate oneMonthFromNow = today.plusDays(30);
	    assertTrue(oneMonthFromNow.isEqual(LocalDate.parse("2014-03-29")));
	 
	    LocalDate nextMonth = today.plusMonths(1);
	    assertTrue(nextMonth.isEqual(LocalDate.parse("2014-03-27")));
	 
	    LocalDate future = today.plus(4, ChronoUnit.WEEKS);
	    assertTrue(future.isEqual(LocalDate.parse("2014-03-27")));
	 
	}

Subtracting From Dates

To subtract days, weeks, months or years from a date there the expected methods: LocalDate.minusDays, LocalDate.minusMonths etc. Here’s some examples of subtracting from a date:

@Test
    public void test_subtract_from_date() {

        assertThat(today.minusWeeks(1).toString(), is("2014-02-20"));

        assertThat(today.minusMonths(2).toString(), is("2013-12-27"));

        assertThat(today.minusYears(4).toString(), is("2010-02-27"));

        Period twoMonths = Period.ofMonths(2);

        assertThat(today.minus(twoMonths).toString(), is("2013-12-27"));

    }

In this example we also introduced the Period object.

Determining Difference Between Dates

It could be argued getting the difference between two dates was the most painful operation to do with dates prior to Java 8. The new Date API makes determining the amount of days,weeks,months or years between dates equally as easy with the LocalDate.until method:

@Test
    public void test_get_days_between_dates() {
        LocalDate vacationStart = LocalDate.parse("2014-07-04");
        Period timeUntilVacation = today.until(vacationStart);

        assertThat(timeUntilVacation.getMonths(), is(4));

        assertThat(timeUntilVacation.getDays(), is(7));

        assertThat(today.until(vacationStart, ChronoUnit.DAYS), is(127L));

        LocalDate libraryBookDue = LocalDate.parse("2000-03-18");

        assertThat(today.until(libraryBookDue).isNegative(), is(true));

        assertThat(today.until(libraryBookDue, ChronoUnit.DAYS), is(-5094L));

        LocalDate christmas = LocalDate.parse("2014-12-25");
        assertThat(today.until(christmas, ChronoUnit.DAYS), is(301L));

    }

In this example we see the use of the Period object again.

Conclusion

We’ve wrapped up our quick tour of the LocalDate and the Java 8 Date API. Obviously, there is so much more to discover about working with dates and time in Java 8, this post is just a quick introduction. Thanks for your time.

Resources

 

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

One Response to "What’s new in Java 8 – Date API"

  1. Very nice article. Thanks for such a nice post.
    Java 8 date and time api seems to be very uniform now.
    I have tried writing a three aritcle series on Java 8 Date and Time API.
    Please read it here : http://java.amitph.com/search/label/date%20and%20time%20api

Leave a Reply


+ two = 11



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books