A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/javaexamples/date_add_time.htm below:

Manipulating and Adding Time to Dates in Java

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:


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4