tl;dr
ZonedDateTime.now( // Capture the current moment as seen with a wall-clock time used by the people of a certain region (a time zone).
ZoneId.of( "America/Los_Angeles" ) // Use proper time zone names in `continent/region` format. Never use pseudo-zones such as `PST` & `EST`.
).withZoneSameInstant( // Adjust from one zone to another. Using immutable objects, so we produce a second distinct `ZonedDateTime` object.
ZoneId.of( "America/New_York" ) // Same moment, different wall-clock time.
)
java.time & ThreeTen-Backport
To gain much of the java.time functionality in Java 7, add the ThreeTen-Backport library to your project.
Generally best to work with UTC values.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Apply a time zone only when required by business logic or display to user.
Your PST
and EST
values are not actual time zones. Use proper time zone names.
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
Apply to the Instant
to get a ZonedDateTime
object. Same moment, same point on the timeline, different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
Adjust to yet another time zone. The java.time framework uses immutable objects. So rather than alter (“mutate”) the original, we product a separate distinct object based on the original’s values.
Both ZonedDateTime
objects and the Instant
all represent the very same moment, the same point on the timeline. This is a crucial concept to understand in date-time handling. Imagine two people, one on the west coast and one on the east coast of North America, talking to each other on the phone. If they both simultaneously look up at the clock hanging on their respective walls, what time do they see? Same moment, different wall-clock time.
ZoneId zNewYork = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdtNewYork = zdt.withZoneSameInstant( zNewYork ) ; // Same moment, different wall-clock time.
All of this has been covered many times already on Stack Overflow. So search for more examples and discussion.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.