This example shows you how to add or subtract hours, minutes or seconds to a date using the java.util.Calendar
object.
package org.kodejava.util;
import java.util.Calendar;
public class DateAddSubtract {
public static void main(String[] args) {
// Gets a calendar using the default time zone and locale. The
// Calendar returned is based on the current time in the default
// time zone with the default locale.
Calendar calendar = Calendar.getInstance();
System.out.println("Original = " + calendar.getTime());
// Subtract 2 hour from the current time
calendar.add(Calendar.HOUR, -2);
// Add 30 minutes to the calendar time
calendar.add(Calendar.MINUTE, 30);
// Add 300 seconds to the calendar time
calendar.add(Calendar.SECOND, 300);
System.out.println("Updated = " + calendar.getTime());
}
}
The output of the code snippet:
Original = Wed Oct 06 19:47:53 CST 2021
Updated = Wed Oct 06 18:22:53 CST 2021
Latest posts by Wayan (see all)
- 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