Skip to content
Advertisement

Adding minutes to LocalDateTime gives error on daylight saving days

I want to add minutes to a LocalDateTime, like this:

 public Timestamp addMinutes(long minutes, LocalDateTime recordDate) {
     LocalDateTime minAddedTime = recordDate.plusMinutes((long) minutes);
     return minAddedTime;

This gives an error on daylight saving dates.

For example my localdatetime = 2021-10-31 02:00:00.0, minutes = 1440 and return value should be 2021-11-01 01:00:00.0. Instead I get 2021-11-01 02:00:00.0.

How should I solve this?

Advertisement

Answer

I used zoned date time to get right answer.

public Timestamp addMinutes(long minutes, Timestamp recordDate) {
        ZonedDateTime zonedDateTime = recordDate.toLocalDateTime().atZone(ZoneId.systemDefault()); 
        LocalDateTime minAddedTime = zonedDateTime.plusMinutes(minutes).toLocalDateTime();
        return Timestamp.valueOf(minAddedTime);

    }
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement