Core Java

Verifying DateTime and Date with Hamcrest

Since I started diving into automated testing and practicing TDD, verification of date values was pain. Luckily there is nice library for legacy Date and new Java 8 DateTime APIs, which cures this pain.

If you belong to healthier part of Java development community and practicing unit testing on daily basis, you probably are aware of Hamcrest Java library. It can make your tests much more readable. It’s architecture is very modular and is used by various other testing libraries.

Major part of it’s flexibility is it concept of Matcher. I am not going to dive into this concept now. If you are not familiar, just take a quick look at Hamcrest tutorial. One of the matcher you can plug into your testing toolbox is library hamcrest-date. With this library we can easily test that date was generated within certain range:

public void validateDate() {
    Date expectedDate = new Date();
    Date actualDate = new Date();
    assertThat(actualDate, DateMatchers.within(2, ChronoUnit.SECONDS, expectedDate));

We can do that also for Java 8 types:

public void validateDateTime() {
    LocalDateTime expectedDateTime =;
    LocalDateTime actualDateTime =;
    assertThat(actualDateTime, LocalDateTimeMatchers.within(2, ChronoUnit.SECONDS, expectedDateTime));

Or pick various exotic verifications hamcrest-core library provides:

public void validateZonedDateTime() {
    ZonedDateTime expectedDateTime = ZonedDateTime.of(2016, 3, 20, 13, 3, 0, 0, ZoneId.of("GMT+1"));
    ZonedDateTime actualDateTime = ZonedDateTime.of(2016, 3, 20, 13, 3, 0, 0, ZoneId.of("GMT-0"));
    assertThat(actualDateTime, ZonedDateTimeMatchers.sameDay(expectedDateTime));
    assertThat(actualDateTime, ZonedDateTimeMatchers.after(expectedDateTime));
    assertThat(actualDateTime, ZonedDateTimeMatchers.isSunday());
    assertThat(actualDateTime, ZonedDateTimeMatchers.isMarch());

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Lubos Krnac

Lubos is a Java/JavaScript developer/Tech Lead and Automation enthusiast. His religion is to constantly improve his developments skills and learn new approaches. He believes TDD drives better design and nicely decoupled code. Past experience includes C++, Assembler and C#.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button