Skip to content

Instantly share code, notes, and snippets.

@michaldabrowski
Last active March 14, 2017 19:01
Show Gist options
  • Save michaldabrowski/29feeabc49c7ea71179791c186f08958 to your computer and use it in GitHub Desktop.
Save michaldabrowski/29feeabc49c7ea71179791c186f08958 to your computer and use it in GitHub Desktop.

(2017) Dates, times, zones in JVM - short guide

Before Java 8

Classes

miliseconds precision, mutable, Joda Time for the rescue

  • java.(util|sql).Date, java.util.Calendar, java.sql.Time, java.sql.Timestamp
  • java.util vs java.sql confusion

SQL types

  • SQL DATE, SQL TIME, SQL TIMESTAMP

  • java.util.Date to java.sql.Date conversion

From docs:

Constructs a Date object using the given milliseconds time value. If the given milliseconds value contains time information, the driver will set the time components to the time in the default time zone (the time zone of the Java virtual machine running the application) that corresponds to zero GMT.

  • java.sql.Date - only date
  • java.sql.Time - only time
  • java.sql.Timestamp - date and time

Java 8+

Classes

All in java.time.*, nanoseconds precision, immutable

  • LocalDate
  • LocalTime
  • LocalDateTime

as seen on a wall clock

  • Instant
  • ZoneId
  • ZoneOffset
  • ZonedDateTime
  • OffsetDateTime

point on the timeline

nanoseconds since 1970-01-01 UTC

ZonedDateTime vs OffsetDateTime

with anomalies vs without anomalies, unstable vs stable ordering, db indexes

Timezone

Time Zone != (Time Zone) Offset

Time Zone = Offset + Rules of Adjustments

Rules of adjustments/anomalies - DST, solar time, Ramadan period etc. in Java8+:

One can determine the correct offset, given a time zone and a datetime. But one cannot determine the correct time zone given just an offset.

In Java8+:

ZonedDateTime = Instant + ZoneId

UTC is also known as Zulu or Z

String representation: 2011-12-03T10:15:30Z

TZDB

https://en.wikipedia.org/wiki/Tz_database https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Timezone Updater Tool

http://www.oracle.com/technetwork/java/javase/tzupdater-readme-136440.html

In practice

  • Do not use pre-Java8 classes

  • Use Joda Time for Java 7 or lower

  • In most cases use Instant to store date with time in DB and model

  • Store Instant as single long column in DB

  • In system where time precision is crucial and you need user TimeZone information (e.g. payments systems, scheduled job services) use ZonedDateTime

  • Store ZonedDateTime as 2 columns in DB: instant (long) + timezone (string) in TZDB format e.g. 'Europe/Warsaw'

  • Use Local* only for birthdays, historical dates, projects strictly connected to one timezone, "clock representation", "demo" projects that are not concerned about dates

TODO

Formatters, date formats, more examples, historical background

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment