Tip of the day #15

Learn and understand java.time objects. Do you need an Instant, a LocalDateTime or a ZonedTimeDate? 11:06 pm, 2th Aug, 2023 is enough for you? Always consider the pitfalls for your use case.

Considerations

Let’s start defining the difference between Instant, LocalDateTime, ZonedDateTime and OffsetDateTime.

Instant

Instant is a point in time, represented by a number of seconds and nanoseconds since the epoch of 1970-01-01T00:00Z ( midnight at the start of 1970 GMT/UTC).

This might be used to record event time-stamps in the application.

LocalDateTime

LocalDateTime is a date-time without a time-zone in the ISO-8601 calendar system, such as 2023-11-13T11:06:00. It is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision.

ZonedDateTime

A date-time with a time-zone in the ISO-8601 calendar system, such as 2023-11-13T11:06:00+01:00 Europe/Paris.

OffsetDateTime

A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2023-11-13T11:06:00+01:00.

Pitfalls

Imagine you have an event to go next month, and you want to save the date and time of the event.

It’s a point in time, so you try to map in an Instant object. Is this work?

public class Event {
    private Instant date;
    // other fields
}

The answer is no. Instant is a point in time, but we don’t know instant ahead of time because it depends on the time zone.

So, we need to use a ZonedDateTime or OffsetDateTime.

And when a ZonedDateTime is not enough? Imagine you have recurring events, like a meeting every Monday.

public class Meeting {
private ZonedDateTime start;
private ZonedDateTime end;
// other fields
}

What is going to happen with the start and end of the meeting when the daylight saving time changes?

This is why we generally add a Duration field to the meeting.

public class Meeting {
private ZonedDateTime start;
private Duration duration;
// other fields
}

We can do it all day, but the lesson is: Always consider the pitfalls for your use case.