Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateUtils.addDays() class issue in daylight saving time

Recently New Zealand observed daylight saving on 27 sept 15.

SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
sd.setTimeZone(TimeZone.getTimeZone("Pacific/Auckland"));
Date dateValue = sd.parse("2015-09-30");
System.out.println(dateValue); // prints "Tue Sep 29 07:00:00 EDT 2015" My local system timzone in EDT 
dateValue = DateUtils.addDays(dateValue, -6); // 6 days back 24 Sep of  Pacific/Auckland
System.out.println(dateValue); // prints "Tue Sep 23 07:00:00 EDT 2015"

The second print statement should print Tue Sep 29 08:00:00 EDT 2015, as Daylight Saving not is in effect.

The issue is before 27 Sep 15 NZ = UTC+12 and after NZ = UTC +13 So on date of 23 Sep It should have time 08:00:00 not 07:00:00

like image 932
M S Parmar Avatar asked Dec 03 '25 02:12

M S Parmar


2 Answers

The problem is within DateUtils.addDays from Apache Commons: it is using a Calendar with the default timezone to add and subtract days instead of using a user-supplied timezone. You can see this in the source code of the method add: it calls Calendar.getInstance() and not Calendar.getInstance(someTimezone)

If you construct yourself the Calendar and set the correct timezone, the problem disappears:

SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
sd.setTimeZone(TimeZone.getTimeZone("Pacific/Auckland"));
Date dateValue = sd.parse("2015-09-30");
System.out.println(dateValue); // prints "Tue Sep 29 13:00:00 CEST 2015"

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Pacific/Auckland")); // set correct timezone to calendar
calendar.setTime(dateValue);
calendar.add(Calendar.DAY_OF_MONTH, -6);
dateValue = calendar.getTime();
System.out.println(dateValue); // prints "Wed Sep 23 14:00:00 CEST 2015"
like image 159
Tunaki Avatar answered Dec 05 '25 15:12

Tunaki


also i have used joda api to resolved this timezone issue.

org.joda.time.DateTimeZone timeZone = org.joda.time.DateTimeZone.forID( "Pacific/Auckland" );
    DateTime currentDate= new DateTime( new Date(), timeZone );
DateTime dateValue = now.plusDays( -6 ); // prints Tue Sep 29 08:00:00 EDT 2015
like image 40
M S Parmar Avatar answered Dec 05 '25 14:12

M S Parmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!