Monday, 1 December 2014

Java 8 Time - choosing the right object

In the last blog post, we looked at the java.time library’s Instant and Duration objects in Java 8. In this second post, we’ll get an overview of some of the other objects within the java.time libraries.

The Instant object is defined in the JavaDocs as “An instantaneous point on the time-line.” There are other objects, related to the Instant, that might also be useful to us – in particular LocalDateTime, LocalDate and LocalTime and ZonedDateTime.

I’ll ignore LocalDate and LocalTime for the moment, and consider LocalDateTime, ZonedDateTime and Instant... all three of these appear to be quite similar, so it’s worth understanding how each differs.

What's the time?

A good starting place is to instantiate each object type with it’s now() method, to get the current time, and to print these out to the console to see what the print formats look like.. the code to do this is shown here, with the output below:

Instant instNow =;
LocalDateTime ldtNow =;
ZonedDateTime zdtNow =;


Ignoring the nano second differences, the formats are interesting. The first, the Instant tells us that this code was ran at 3.18pm on 1st December 2014. The letter z at the end stands for Zulu time, which is also known as GMT (Grenwich Mean Time) or UTC (which stands for Coordinated Universal Time… I don’t know why it’s not abbreviated to CUT – I’ll leave you go to go searching on Wikipedia if you want to know more about this!) So the first item, the Instant, is 3.18pm on 1st December 2014 UTC.

The second result is the local date time – that’s a representation of my current time, which is 3.18pm on 1st December 2014, that's what my computer clock and calendar say. And the third item is the zoned date time, where we can again see that it’s 3.18pm on 1st December 2014, London time.

This all looks very neat because I’m in the UK, where the timezone is GMT (at least in Winter)… what would have happened if I was somewhere else in the world?

Well here’s what a person in Abu Dhabi who tried the same exercise would find...


So now we can see that the Instant is the same point on the timescale as the person in London found, but their LocalDateTime was the time their clock shows (4 hours later than the person in London’s clock) and the ZonedDateTime matches the LocalDateTime but it has the time-zone embedded in.

Let’s dig a little deeper into the definitions of these objects…

An Instant is an actual point in time, expressed using UTC – a universal time scale. A ZonedDateTime is an actual point in time, but in a specific area of the world... so if you know the timezone you can convert reliably from an Instant to a ZonedDateTime. A LocalDateTime is a representation of the concept of a date and time, but doesn’t actually correspond to an actual point in time… or rather it can only be converted into an actual point in time if we ADD IN a timezone.

Although LocalDateTime objects don’t necessarily correspond to an actual point in time, you can still do all the “date mathematics” you might want to with them, such as adding or subtracting days, minutes or nanoseconds.

Ok so how is this useful?

If you’re writing code that is going to manipulate dates, you now have a choice of what to use. In the United Kingdom, our clocks go forward for an hour in the summer, (known as daylight saving) so at some times in the year we are effectively operating at GMT and sometimes it’s GMT+1.

This could cause confusion on the dates the clocks go back an hour from GMT+1 to GMT... the change happens at 2am – this year it was on Sunday October 26th. What this means is that if I looked at my digital clock, the minutes on Sunday 26th October changed like this…


As a result, the time 01:30am happened twice on 26th October…. At least as far as my clock is concerned. But my clock operates on LocalDateTime (or it would if it were running Java) – if I had an InstantClock it would have looked like this:


And if had a ZonedDateTime clock it might have looked like this:

01:58 BST
01:59 BST
01:00 GMT
01:01 GMT

(BST stands for British Summer Time – it’s another way of saying GMT+1)

Now let’s suppose we were writing code that was going to run a critical piece of functionality each night at 1.30am. For example, maybe we are a bank, and it’s at 1.30am that our function starts that is going to calculate the daily interest on every customer's account. It would be important not to use a LocalDateTime object for this code, as it might run twice on 26th October (and not at all on 30th March 2014, the date that the clocks skipped an hour). In this example, I’d want to use an Instant - I want my critical process to run at fixed times on the time-line.

In fact if I was coding up a system for a bank, that was recording every transaction in every account, I’d probably want to store the date and time for each transaction as an Instant object… that way I know exactly when it happened…. And because bank transactions can occur between countries, it makes sense to know the date and time of each transaction based on UTC, and then translate that into a local date and time for each country’s reports.

So if we go on to write another piece of code that details, for example, the number of transactions by hour while the bank was open each day, for this we would want to use the ZonedDateTime object, to query transactions between fixed times in each location… this can tell us how many transactions occurred between 9am and 10am LOCAL time (the first hour of opening) in each country.

LocalDate and LocalTime

As you might suspect from their names these objects store a date or a time in isolation… and in fact a LocalDateTime is actually a combination of LocalDate and LocalTime… and the LocalDateTime object has a toLocalDate() and toLocalTime() method to easily extract each component.

Now I think these are particularly useful, well LocalDate is. I often find I want to compare 2 dates ignoring their time values. I’ve traditionally used the Apache Commons DateUtils library in the past to help with this – it has a truncatedCompareTo method which allows you to say compare 2 dates but only consider (for example) the date part, or only consider the year and month.

Now you might think that you could do this with the Instant objects... consider this code for example:

Instant instant1 = Instant.parse("2014-12-01T16:01:13.419Z");
Instant instant2 = Instant.parse("2014-12-17T15:17:22.305Z");

Here we have two dates - the 1st December at 4.01pm, and the 17th December at 3.17pm. I'd like to know how many days there are between these two dates, ignoring the times. The answer should be 17 less 1 = 16.

However the output from my println is... 15. The reason is that there are actually 15 days, 23 hours and 43 minutes between these two dates and our .toDays() method tells us that's 15 days - it ignores the hours and minutes.

So how do we find out the real number of days, ignoring the time?

Well here's some code that will do this:

Instant instant1 = Instant.parse("2014-12-01T16:01:13.419Z");
Instant instant2 = Instant.parse("2014-12-17T15:17:22.305Z");
LocalDate d1 = LocalDateTime.ofInstant(instant1, ZoneId.systemDefault()).toLocalDate();
LocalDate d2 = LocalDateTime.ofInstant(instant2, ZoneId.systemDefault()).toLocalDate();

In this code, we're taking 2 different Instant objects, converting them into LocalDate objects (note that we need to first convert them to LocalDateTimes... and I've just used the system default's time zone for the conversion), and then looking at how many days there are between the two local dates. We get the answer we're looking for - 16.

But this introduces another new object - that of the Period. When we compared 2 Instants in the previous blog post, we used the Duration object - well if you try and compare 2 LocalDates with a Duration object you'll find it will compile but you'll get a rather horrible looking UnsupportedTemporalTypeException.

So I guess we need to finish by understanding what the Period object is...

Periods or Durations

Well the official definition is that whereas the Duration object works with time - that is hours, minutes and seconds, whereas a Period object works with dates - or rather years, months and days. In reality I find you can forget this and just remember that if you're working with LocalDate you must use Period, if you're working with Instant, LocalDateTime, or ZonedDateTime use Duration.

Admittedly it's not that simple (nothing is really with Java Time) - there's a rather interesting note in the JavaDocs that says that a Duration of 1 day will always be 24 hours, but a period of 1 day might be 23, 24 or 25 hours due to the impacts of daylight saving time changes.

Confused? yes I am too - I guess until we have all been building lots of code that manipulate dates we won't be completely familiar with which is the best object type to use and when, but I do at least get a sense that the structure of java.time is comprehensive. So far I haven't found any aspect of date manipulation or date mathematics that I can't do with java.time, although it can sometimes take what feels like quite a lot of effort.

So has Java finally come up with a replacement for Date that works? Well I want to say yes... It's a cautious yes for now but if I'm honest, I like what I'm using!


  1. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.

  2. Where does OffsetDateTime fit in the whole mix? I've seen it mentioned that OffsetDateTime should be used when storing date/times with timezone in a database.

  3. Question. In your example where daylight savings comes into effect. Say we create LocalDateTime before =; and then after the time changes we do Duration.between(before,; What will the duration show? Under the hood, is it actually using instants or will it show a negative duration?

  4. Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's. 
    best rpa training in bangalore
    rpa training in bangalore | rpa course in bangalore
    RPA training in bangalore
    rpa training in chennai
    rpa online training

  5. I was recommended this web site by means of my cousin. I am now not certain whether this post is written through him as nobody else recognise such precise about my difficulty. You're amazing! Thank you!
    Data Science Tutorial
    Data Science training in anna nagar
    Data science training in jaya nagar
    Data science training in pune
    Data Science Training in Marathahalli
    Data science training in kalyan nagar

  6. I enjoy what you guys are usually up too. This sort of clever work and coverage! Keep up the wonderful works guys I’ve added you guys to my blog roll.
    python Course in Pune
    python Course institute in Chennai
    python Training institute in Bangalore

  7. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging.
    AWS Training in Bangalore

    AWS Training in pune

  8. I enjoy what you guys are usually up too. This sort of clever work and coverage! Keep up the wonderful works guysl.Good going.
    honor service center velachery
    honor service center in vadapalani

  9. Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
    python training in bangalore


  10. Just saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab Python training in pune your rss feed to stay informed of any updates.

  11. I love the way you write Business Analytics Online Course and share your niche! Very interesting and different! Keep it coming!

  12. Attend The Analytics Training Institute From ExcelR. Practical Analytics Training Institute Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Analytics Training Institute.
    ExcelR Analytics Training Institute

  13. I finally found great post here.I will get back here. I just added your blog to my bookmark sites. thanks.Quality posts is the crucial to invite the visitors to visit the web page, that's what this web page is providing.
    ExcelR Data Analytics Course

  14. I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work. data science course fees in Bangalore

  15. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!
    data analytics courses
    data science courses
    business analytics course

  16. I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.
    data analytics course mumbai

  17. Attend The Artificial Intelligence course From ExcelR. Practical Artificial Intelligence course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Artificial Intelligence course.
    ExcelR Artificial Intelligence course

  18. keep up the good work. this is an Ossam post. This is to helpful, i have read here all post. i am impressed. thank you. this is our Data Science course in Mumbai
    data science course in mumbai |

  19. This is a wonderful article, Given so much info in it, Thanks for sharing. CodeGnan offers courses in new technologies and makes sure students understand the flow of work from each and every perspective in a Real-Time environmen python training in vijayawada. , data scince training in vijayawada . , java training in vijayawada. ,

  20. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!

    business analytics course

    data analytics courses

    data science interview questions

    data science course in mumbai

  21. I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!
    machine learning course pune

  22. wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries.
    Data science Interview Questions
    Data Science Course

  23. wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries. keep it up.
    data analytics course in Bangalore

  24. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. ExcelR Data Science Courses Any way I’ll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info.