javaandroidcalendardstgregorian-calendar

How Can I Make My Calendar Ignore DST Adjustments?


I’m trying to calculate the time by adding minutes to given date-time. It’s works well with other times but not for the DST times [ Canada Eastern time ].

 public static GregorianCalendar addMinuts(GregorianCalendar newDate, int minutes) {
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(newDate.getTime());

        Log.i("UtilApp", "expiry date before add minutes " + cal.getTime());
        cal.add(Calendar.MINUTE, minutes);
        Log.i("UtilApp", "expiry date after add " + minutes + " minutes " + cal.getTime());
        return setGreCalendar(cal.getTime());
    }

 public static GregorianCalendar setGreCalendar(Date date) {
        Date date1;
        GregorianCalendar gregorianCalendar = new GregorianCalendar();
        if (date != null) {
            date1 = date;
            gregorianCalendar.setTime(date1);
        }
        return gregorianCalendar;
    }

For example:- I added 225 minutes which is 3 hrs and 45 minutes to 9th march, and it gives the exact date and time as DST is not in effect.

9th march

While on March 10th, DST is in effect, so instead of getting 03:45, I get 04:45 with the same 225 minutes. The calendar is skipping the time between 2:00 and 3:00 due to DST.

10th March

I want it to ignore the DST adjustments. I tried with the time-zone, Local date-time but it didn’t work as expected. Any help would be appreciated.


Solution

  • You wrote (in your question):

    I tried with the time-zone, Local date-time but it didn’t work as expected.

    I don't know if you are referring to class LocalDateTime, because if you are then it should work as you expect since class LocalDateTime has no time zone whereas class Calendar does which its subclass, GregorianCalendar, inherits.

    The below code gives your expected result when adding minutes to a LocalDateTime, regardless of daylight savings adjustments.

    import java.time.LocalDate;
    import java.time.LocalDateTime;
    import java.time.temporal.ChronoUnit;
    
    public class AdMinute {
    
        public static void main(String[] args) {
            LocalDate ld = LocalDate.of(2024, 3, 10);
            LocalDateTime ldt = ld.atStartOfDay();
            System.out.println("Org: " + ldt);
            System.out.println("Add: " + ldt.plus(225, ChronoUnit.MINUTES));
        }
    }
    

    Here is the output when running the above code:

    Org: 2024-03-10T00:00
    Add: 2024-03-10T03:45
    

    Note that I am in Israel and our daylight savings started at March 29. At 2:00 am clocks were moved forward to 3:00 am. If I replace the date, in the above code, with 29 (rather than 10), I still get the same result. Hence using LocalDateTime is not affected by daylight savings adjustments.

    Refer to this tutorial.