chris09trt
chris09trt

Reputation: 91

how can i skip changing time-zone using calendar in java?

i have an issue skipping the time-zone using calendar. My problem sounds like this : I have an event starting "x" date and i have to add hours but not changing the clock time. For example if my event its 2019-03-09 22:46:00 and i add 2400 hours (100 days) , my output will be "2019-06-17 23:46:00" because of time-zone changing. I need my out put to be 2019-06-17 22:46:00. How can i make that using calendar ? calendar = my first event date calendar2 = the date after i need to return my next event by adding hours to first calendar.

while (calendar.compareTo(calendar2) < 0) {
            calendar.add(Calendar.HOUR_OF_DAY, nr_hours);
        }
        nextEvent =sdf.format(calendar.getTime());
        return nextEvent;

Upvotes: 3

Views: 105

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338366

tl;dr

LocalDateTime
.parse( "2019-03-09T22:46:00" )
.plus( 
    Duration.ofDays( 100 )
)

See this code run live at IdeOne.com.

2019-06-17T22:46

Details

or example if my event its 2019-03-09 22:46:00 and i add 2400 hours (100 days) , my output will be "2019-06-17 23:46:00" because of time-zone changing.

Do you understand that the 11 PM in 17th is indeed 2400 hours later than 10 PM on the 9th in your particular time zone? If you report the end as 10 PM in the context of that time zone, your result will be interpreted by the reader as a moment 2399 hours after the start.


Never use the terrible classes Calendar or Date. These legacy classes were supplanted years ago by the modern java.time classes defined in JSR 310.


If you are certain you want to ignore the reality of time zone changes, use LocalDateTime.

LocalDateTime start = LocalDateTime.parse( "2019-03-09T22:46:00" ) ;
Duration d = Duration.ofDays( 100 ) ;  // Days in `Duration` are generic 24 hours chunk of time without regard for dates and calendar. Same effect as `Duration.ofHours( 2_400 )`.
LocalDateTime end = start.plus( d ) ;

Upvotes: 3

Related Questions