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!