In this example you will learn how to add hours, minutes or seconds to a DateTime
object in Joda-Time. Some methods are available to add or subtract hours, minutes or seconds from the object, as you can see in the example below.
The DateTime
object is an immutable object, which means calling one of the plus()
or minus()
method does not modify the current object. Instead, these methods return a new DateTime
object for each method calls.
In the code snippet below we call the plus()
and minus()
method without storing the result of the operation, we are only going to print it out. The get the new value of the DateTime
object you need to assign it to a variable.
package org.kodejava.joda;
import org.joda.time.DateTime;
public class TimeCalculationDemo {
public static void main(String[] args) {
// Creates an instance of current DateTime which represents the
// current date time.
DateTime dateTime = new DateTime();
System.out.println("DateTime = " + dateTime);
// Plus some hours, minutes, and seconds to the original DateTime.
System.out.println("Plus 60 seconds is = " + dateTime.plusSeconds(60));
System.out.println("Plus 10 minutes is = " + dateTime.plusMinutes(10));
System.out.println("Plus 1 hour is = " + dateTime.plusHours(1));
// Minus some hours, minutes, and seconds to the original DateTime.
System.out.println("Minus 60 seconds is = " + dateTime.minusSeconds(60));
System.out.println("Minus 10 minutes is = " + dateTime.minusMinutes(10));
System.out.println("Minus 1 hour is = " + dateTime.minusHours(1));
}
}
The program print the following result. The output shows the result of adding or subtracting seconds, minutes and hours the the DateTime
object.
DateTime = 2021-10-31T22:56:55.715+08:00
Plus 60 seconds is = 2021-10-31T22:57:55.715+08:00
Plus 10 minutes is = 2021-10-31T23:06:55.715+08:00
Plus 1 hour is = 2021-10-31T23:56:55.715+08:00
Minus 60 seconds is = 2021-10-31T22:55:55.715+08:00
Minus 10 minutes is = 2021-10-31T22:46:55.715+08:00
Minus 1 hour is = 2021-10-31T21:56:55.715+08:00
Maven Dependencies
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.12.7</version>
</dependency>