Using java.time
You should be using java.time classes rather than the troublesome old date-time classes such as Calendar
than are now legacy.
Be sure to read the class doc for ZonedDateTime
to understand its choice of how to handle the Daylight Saving Time (DST) cut-overs.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or EDT
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/New_York" );
// of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond, ZoneId zone)
ZonedDateTime zdt = ZonedDateTime.of( 2016 , 11 , 6 , 1 , 26 , 16 , 0 , z );
ZonedDateTime zdtOneHourEarlier = zdt.minusHours( 1 );
ZonedDateTime zdtOneHourLater = zdt.plusHours( 1 );
Note the offset-from-UTC in each result.
zdt.toString(): 2016-11-06T01:26:16-04:00[America/New_York]
zdtOneHourEarlier.toString(): 2016-11-06T00:26:16-04:00[America/New_York]
zdtOneHourLater.toString(): 2016-11-06T01:26:16-05:00[America/New_York]
See this code run live at IdeOne.com.
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.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
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.