0

I am seeing this issue while using Calendar instance to subtract one hour from time when day light saving ends and we transition to standard time. here is the code:

 Date startTime = new Date();// Gives me Sun Nov 06 01:26:16 EST 2016
Calendar temp;
TimeZone timezone = TimeZone.getDefault(); //Eastern
temp= Calendar.getInstance(timezone);
temp.setTime(startTime);
temp.add(Calendar.HOUR_OF_DAY, -1);
 temp.set(Calendar.MILLISECOND, 0);
    Date endDate =  temp.getTime(); // This is still Sun Nov 06 01:26:16 EST 2016

The result that I expect in endDate is Sun Nov 06 01:26:16 EDT 2016 instead of Sun Nov 06 01:26:16 EST 2016. I am not sure if this is as designed or not. If I subtract 2 hours, then I see it working fine. Any inputs on this?

Thanks, SS

SS05
  • 1
  • 2

1 Answers1

1

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?

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.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154