Search code examples
javadstjava-timezoneddatetime

Getting wrong result after Subtracting a day from a date Using LocalDateTIme and ZonedDateTime


I am testing with "2016-03-28T02:00:00+0200" (1459123200 in UTC Sec.)

After subtracting 1 day, DST is applied and output should be:

"2016-03-27T03:00:00+0200"

But I am getting this:

2016-03-26T01:00+01:00[Europe/Stockholm]

CODE:

public class DateFormatSampleCode {
    public static void main(String[] args) 
    {
        LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(1459123200, 0, ZoneOffset.UTC);

        System.out.println(localDateTime);
        localDateTime = localDateTime.minusDays(1);
        System.out.println(localDateTime);

        ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Europe/Stockholm"));

        System.out.println(zonedDateTime);
    }
}

Please check and point out where I am going wrong.


Solution

  • I think I can answer my above question.

    Here is the code.

    public ZonedDateTime addDays(long myUTCTimeInSeconds, int days) {
        Instant instant = Instant.ofEpochSecond(myUTCTimeInSeconds);
        ZonedDateTime dateTimeWithOffSet = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
        if (localDays >= 0) {
            dateTimeWithOffSet = dateTimeWithOffSet.plusDays(localDays);
        } else {
            dateTimeWithOffSet = dateTimeWithOffSet.minusDays(abs(localDays));
        }
        return dateTimeWithOffSet;
    }
    

    If the timezone is different from that of system, we can set the Default TimeZone and after calling above method reset the timezone as:

    TimeZone systemDefaultTimeZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone(timezone));
    
    addDays(1459123200, 1);
    TimeZone.setDefault(systemDefaultTimeZone);