Date and Time

Java 8 time API

Java 8 time API is designed mainly to handle

  1. Dates
  2. Times
  3. Instants
  4. Durations

Time API is

  1. Based on ISO calendar system
  2. Follows Gregorian rules
  3. Immutable and Thread-safe

Try using java 8 API wherever possible, It gives you an easy to use and manageable library to handle all date utils

Dates and Times

  • How do you store passport issued and expiry date?
  • How do you set an alarm to wake up?
  • How do you store the birth date and time?
  • How do you store the International travel date and time?

The following classes give you the way to solve it

LocalDate: Stores a date without a time. Ex: ‘2010-12-03’.

LocalTime: Stores a time without a date. Ex: ’11:30′.

LocalDateTime: Stores date and time. Ex: ‘2010-12-03T11:30’.

ZonedDateTime: Stores date and time with a time-zone.

Instant

  • Is essentially a numeric timestamp. This is useful for logging and persistence of a point in time.
  • Try using Clock and Instance whenever you need System.currentTimeMillis().
  • Instant is the closest equivalent class to java.util.Date. ZonedDateTime

Duration and Period

Beyond dates and times, the API also allows the storage of periods and durations of time.

Month: This stores a single month-of-year in isolation. Ex ‘DECEMBER’.

DayOfWeek: This stores a single day-of-week in isolation. Ex ‘TUESDAY’.

Year: This stores a single year in isolation. Ex: ‘2010’.

YearMonth: This stores a year and month. Ex: ‘2010-12’

MonthDay: This stores a month and day-of-month. Ex: ‘–12-03’ (12th March)

OffsetTime: Stores a time and offset from UTC without a date. This stores a date like ’11:30+01:00′. The ZoneOffset is of the form ‘+01:00’.

OffsetDateTime: Stores date and time and offset from UTC. This stores a date-time like ‘2010-12-03T11:30+01:00’. This is sometimes found in XML messages and other forms of persistence but contains less information than a full time-zone.