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 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
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
with anomalies vs without anomalies, unstable vs stable ordering, db indexes
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
https://en.wikipedia.org/wiki/Tz_database https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
http://www.oracle.com/technetwork/java/javase/tzupdater-readme-136440.html
-
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
Formatters, date formats, more examples, historical background