
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
Manipulating and Adding Time to Dates in Java
Manipulating date and time can be achieved by adding or subtracting specific time units like days, years, or seconds using the Calendar class in Java. The add() method of the Calendar class allows you to modify the date by a specified amount of time.
Adding Time (Days, Years, Seconds) to Date
To add time in a date, you can use the Java Date setTime(long time) method that sets this Date to show time milliseconds after January 1, 1970, 00:00:00 GMT. This method is defined in the Calendar class, which provides methods for manipulating dates and times in a calendar-specific way.
Syntax
Following is the declaration for java.util.Date.setTime() method
public void setTime(long time)
add() method: The add() method in the Calendar class that adds or subtracts a specified amount of time (such as days, months, years) to the current date.
Java Program for Adding Time to a Date
The following example shows us how to add time to a date using the add() method of Calendar
import java.util.*; public class Main { public static void main(String[] args) throws Exception { Date d1 = new Date(); Calendar cl = Calendar. getInstance(); cl.setTime(d1); System.out.println("today is " + d1.toString()); cl. add(Calendar.MONTH, 1); System.out.println("date after a month will be " + cl.getTime().toString() ); cl. add(Calendar.HOUR, 70); System.out.println("date after 7 hrs will be " + cl.getTime().toString() ); cl. add(Calendar.YEAR, 3); System.out.println("date after 3 years will be " + cl.getTime().toString() ); } }
Output
today is Mon Jun 22 02:47:02 IST 2009 date after a month will be Wed Jul 22 02:47:02 IST 2009 date after 7 hrs will be Wed Jul 22 09:47:02 IST 2009 date after 3 years will be Sun Jul 22 09:47:02 IST 2012
Code Explanation
The Calendar class is used to add time to the current date. The setTime() method is used to initialize the Calendar object with the current date (d1). Then, the add() method is called multiple times to add different amounts of time:
Adding one month: cl.add(Calendar.MONTH, 1) adds 1 month to the current date.
Adding 70 hours: cl.add(Calendar.HOUR, 70) adds 70 hours to the current date.
Adding 3 years: cl.add(Calendar.YEAR, 3) adds 3 years to the current date. The updated dates are printed after each operation, showing how the date changes with the addition of time.