Add hours, minutes or seconds to a date in Java

Description

The following code shows how to add hours, minutes or seconds to a date.

Example


/*  www .  j av a 2 s.c  om*/
import java.util.Calendar;
 
public class Main {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        System.out.println("Original = " + calendar.getTime());
 
        // Substract 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 code above generates the following result.





















Home »
  Java Tutorial »
    Date »




Date Get
Date Set
Date Format
Date Compare
Date Convert
Date Calculation
Date Parse
Timezone