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 = Instant.now();
LocalDateTime ldtNow = LocalDateTime.now();
ZonedDateTime zdtNow = ZonedDateTime.now();
System.out.println(instNow);
System.out.println(ldtNow);
System.out.println(zdtNow);

2014-12-01T15:18:31.094Z
2014-12-01T15:18:31.109
2014-12-01T15:18:31.152Z[Europe/London]


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...

2014-12-01T15:18:31.094Z
2014-12-01T19:18:31.109
2014-12-01T19:18:31.152+04:00[Asia/Muscat]


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…

01:58
01:59
01:00
01:01


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:

00:58
00:59
01:00
01:01


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");
System.out.println(Duration.between(instant1,instant2).toDays());

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();
System.out.println(Period.between(d1,d2).getDays());

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!

40 comments:

  1. 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.

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

    ReplyDelete
  3. 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

    ReplyDelete
  4. 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

    ReplyDelete
  5. 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

    ReplyDelete
  6. 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

    ReplyDelete
  7. I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.
    Data Analytics Course Pune wow... what a great blog, this writter who wrote this article it's realy a great blogger, this article so inspiring me to be a better person in some of them hope you will give more information on this topics in your next articles.
    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!

    ReplyDelete
  8. This is such a great article. Thank you so much! In case of REST APIs, what would be recommended type to use?

    ReplyDelete
  9. It's late finding this act. At least, it's a thing to be familiar with that there are such events exist. I agree with your Blog and I will be back to inspect it more in the future so please keep up your act.
    data scientist course in hyderabad

    ReplyDelete
  10. Amazing article! good to read and informative content.

    Data Science Training in Pune

    ReplyDelete
  11. Extremely Overall Quite Fascinating Post. I Was Searching For This Sort Of Data And Delighted In Perusing This One. Continue Posting. A Debt Of Gratitude Is In Order For Sharing. Best Institute For Cloud Computing In Hyderabad

    ReplyDelete
  12. I am impressed by the information that you have on this blog. It shows how well you understand this subject.
    data scientist course in malaysia

    ReplyDelete
  13. Informative and knowledgeable content, big thumps up for your article. Keep sharing more stuff like this. Thank you.
    Data Scientist Training in Hyderabad

    ReplyDelete


  14. Awesome blog. Thanks for sharing this blog. Keep update like this...
    Android Training in Bangalore
    Android Classes in Pune

    ReplyDelete
  15. Thanks for such a great post and the review, I am totally impressed! Keep stuff like this coming.
    business analytics training in hyderabad

    ReplyDelete
  16. https://www.ecomena.org/big-data-and-environmental-sustainability/?unapproved=149421&moderation-hash=6bfb8ee98a1adc99df13d7b873c5c3e8#comment-149421

    ReplyDelete
  17. Big Data or the 'unstructured' data produced by individuals every day in the form of photos, messages,
    or videos that are not structured in form, so a data scientist is basically there to arrange this data more flowing manner.
    data analyst course in pune

    ReplyDelete
  18. With a distinctive curriculum and methodology, our Data Science certification programme enables you to secure a position in prestigious businesses. Use all the advantages to succeed as a champion.data science course institute in nagpur

    ReplyDelete
  19. Vidal International's Data Science Course in Vizag offers comprehensive training in the field of data science. Learn essential skills such as data analysis, machine learning, and predictive modeling from industry experts. Gain hands-on experience through practical projects and develop the expertise to extract valuable insights from complex datasets. Join our course and embark on a rewarding journey in the world of data science.

    ReplyDelete

  20. Your contribution of valuable information on B.Com colleges in Hyderabad is truly appreciated. Thank you!
    Colleges In Hyderabad For B.com

    ReplyDelete
  21. Appreciate the valuable info on the top MEC Intermediate colleges in Hyderabad
    Best Intermediate Colleges For MEC In Hyderabad

    ReplyDelete
  22. I never stop myself to express something about your nice work. You're working really hard. Azure Data Factory Training in Hyderabad

    ReplyDelete
  23. This post is a great introduction to the Java 8 Time API. It clearly explains the different types of objects available and how to use them. I especially like the examples that show how to use the different objects to solve real-world problems. Thank you.
    Data Analytics Courses in Nashik

    ReplyDelete
  24. The blog is excellent, and I appreciate you sharing the best information.
    CMA Coaching Institutes in Hyderabad

    ReplyDelete
  25. The author provides a comprehensive and informative overview of Java 8's java.time library, explaining the differences between various time-related objects with clear examples. A valuable resource for anyone working with dates and times in Java.
    Data Analytics Courses In Dubai

    ReplyDelete
  26. Visiting your website is awesome and wonderful. I appreciate you giving this knowledge because I will find it beneficial.
    Colleges In Hyderabad For B.com


    ReplyDelete
  27. It was fantastic and wonderful to visit your website. I value your sharing this information since I will find it useful.
    Data Analytics Courses in Agra

    ReplyDelete
  28. I would like to thank you for your efforts in this wonderfully detailed post on Java 8 Time API. I just really loved the way concisely you have explained this topic in points. I am definitely going to share it with my friends.
    Visit - Data Analytics Courses in Delhi

    ReplyDelete
  29. nice blog
    Data Analytics Courses In Vadodara

    ReplyDelete
  30. The blog post provides comprehensive overview on Java 8 Time API!
    Digital Marketing Courses in Italy

    ReplyDelete
  31. Greatly informative and well-informed stuff; many thanks for your essay. Please provide more content of this kind. I'm grateful.
    Colleges for BBA In Hyderabad

    ReplyDelete
  32. "Great article on Java 8 time! I appreciate the insights on choosing the right object for handling time-related operations. The explanation on LocalDate, LocalTime, and LocalDateTime was particularly helpful. Looking forward to more content on Java development!"
    Best Data analytics courses in India

    ReplyDelete
  33. The blog effectively demystifies the Java 8 Time API, making it accessible for developers seeking clarity on selecting the appropriate temporal object for specific scenarios. It is a helpful resource for those grappling with time management in Java programming.
    Data analytics framework

    ReplyDelete