Louis Louis - 1 month ago 4x
Java Question

Adding java time objects

How do you say, add 1 hour to a given result from calendar.getTime?



ZonedDateTime.now( ZoneId.of( "America/Montreal"  ).plusHours( 1 ) 

Using java.time

The accepted Answer is correct but outdated.

The troublesome old legacy date-time classes have been supplanted by the java.time classes.

Instead of Calendar, use ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( z );
ZonedDateTime zdtOneHourLater = zdt.plusHours( 1 );

Note that the wall-clock time may not be an hour later. Anomalies such as Daylight Saving Time (DST) means an hour later may appear to be two hours later jumping from 1 AM to 3 AM for DST switch-over.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to useā€¦).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.