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>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
It not working as expected. Here is my code and result.
Result:
Date Time :2016-08-29T03:31:39.047+07:00
Date Time :2016-08-29T03:31:39.047+07:00
Date Time :2016-08-29T03:31:39.047+07:00
Hello Hien Khuu,
Joda-Tme objects are immutable. When you change the property of a
DateTime
object it will not change the current object, instead it will return a new copy. You need to assign the modification result into a new object to get the modified value.For example:
Or you could combine the operation: