3

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

Tunaki
  • 132,869
  • 46
  • 340
  • 423
M S Parmar
  • 955
  • 8
  • 22

2 Answers2

3

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"
Tunaki
  • 132,869
  • 46
  • 340
  • 423
1

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
M S Parmar
  • 955
  • 8
  • 22
  • In Java 8 and later, you can use the new built-in [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) framework. These new classes were inspired by Joda-Time and are intended to be its successor. – Basil Bourque Oct 02 '15 at 07:42