0

I am subtracting 24 hours from a GregorianCalendar 03/25/2018 09:41.

Result 03/24/2018 08:41.

public class Utiles{
    public static void main(String args[]) {

        SimpleDateFormat sdt = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        GregorianCalendar gcFinAux = new GregorianCalendar(2018, 2, 25, 9, 41, 0);

        System.out.println("1. " + sdt.format(gcFinAux.getTime()));
        gcFinAux.add(Calendar.HOUR_OF_DAY, -24);
        System.out.println("2. " + sdt.format(gcFinAux.getTime()));
    }
}

Output:

1. 25/03/2018 09:41:00
2. 24/03/2018 08:41:00

If I try with another date the result is correct.

I try in Linux and Windows with JDK1.6.0_45 and Java 1.8.

Could someone confirm if you get the same results?

Thank you.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161

2 Answers2

0

I know some parts of the world have time changes during that specific 24 hr period. Sounds like the underlying logic is taking that into account.

Chris Gerken
  • 16,221
  • 6
  • 44
  • 59
0

As has been said in the comments, what you observed is the expected and correct behaviour in time zones that change to summer time (DST) during the night between March 24 and March 25 this year. This includes most of Europe including Spain, not (the European parts of) Turkey and Russia, but also for example Greenland and Lebanon (while Paraguay changes back from summer time the same night).

java.time: As lexicore and Zabuza said in comments, there is really no reason why you should want to use SimpleDateFormat and GregorianCalendar. Those classes are long outdated and the former in particular notoriously troublesome. Instead use java.time, the modern Java date and time API:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
    ZonedDateTime zdtFinAux 
            = ZonedDateTime.of(2018, 3, 25, 9, 41, 0, 0, ZoneId.of("Europe/Madrid"));

    System.out.println("1. " + zdtFinAux.format(formatter));
    zdtFinAux = zdtFinAux.minusHours(24);
    System.out.println("2. " + zdtFinAux.format(formatter));

The output is the same as yours, of course:

1. 25/03/2018 09:41:00
2. 24/03/2018 08:41:00

If you wanted the same time of day on the previous day, one option is to use minusDays(1) instead of minusHours(24).

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161