Search code examples
javadatedatetimedst

Date format error when use Brazilian Summer Time (BRST)


I'm having a problem when removing the time from a variable date (Sun Oct 21 01:00:00 BRST 2018) because it is generating a billing error when a data comes from the database with that 1 hour difference.

This only happens when it is the first day of summer time in Brazil

I've already tried using the Calendar class.

public static Date zeroTimes( final Date data ) {
        Calendar cal = Calendar.getInstance();
        cal.setTime( data );
        cal.add( Calendar.HOUR, - 1 );
        return cal.getTime();

    }

The return of this method is this Sun Oct 21 01:00:00 BRST 2018, but what is expected is Sun Oct 21 00:00:00 BRST 2018


Solution

  • There are two issues here:

    • Your JVM has stale time zone data
    • You're trying to subtract one hour from 1am where midnight doesn't exist on that date according to the stale time zone data.

    In December 2017, the Brazilian government changes the rules for daylight saving time so that summer time starts on the first Sunday in November. See this page in Portuguese or this page in English for references.

    So while summer time in 2018 actually starts on November 4th, it looks like your JVM believes it starts on October 21st. If that were the case, 12am wouldn't exist, so 1am would be shown as the start of that date. You haven't told us what value you've got in the Date object, but I expect that to be the problem.

    Firstly, I'd stop using java.util.Date if you possibly can. The java.time types are much better, in many ways. Use the JSR-310 backport if you're stuck on an old version of Java.

    Secondly, update your time zone data. See this page for more information.

    Thirdly, work out how you want to handle DST transitions. This is somewhere we probably can't give much advice other than a) think about it explicitly; b) write lots of tests. The exact details of what you'll need to do will depend on your business rules. (It's very likely in my experience that the person who decides those business rules may not have thought about this yet either. Don't let them hand-wave it away: demand precise specifications. Politely, of course :)