Home » Java programs » Java date, time programs

Program to add given hours in current date and time in java



Here, we are implementing a java program that will read number of hours to be added in the current date and time. This program is adding hours in the current date, time.
Submitted by IncludeHelp, on December 24, 2017

Given number of hours and we have to add this in the current date, time using java program.

This program is reading current date, time first and then adding given number of hours (that is defined in the source code; we can also read it from the user). And finally printing the updated (new) date and time.

Example

    Input
    Current Date : 12-23-2017
    Current time : 20:36:24

    Outot (After adding 15 hours)
    New Date : 12-24-2017
    New time after adding 15 hours : 11:36:24

Program

package IncludeHelp;

import java.util.Calendar;

public class ExAddHrsToCurrentDate
{
	public static void main(String[] args)
	{
		// create object of calendar class.
		Calendar now = Calendar.getInstance();

		// fetch the Current date and time of the system.
		System.out.println("Current Date : " + (now.get(Calendar.MONTH) + 1) +
		"-"+ now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
		System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) +
		":"+ now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));

		// take default hours.
		now.add(Calendar.HOUR, 15);

		//printng date after adding 15 hours in time
		System.out.println("New Date : " + (now.get(Calendar.MONTH) + 1) + "-"+
		now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));	
		// This will show new time and date after adding hours.
		System.out.println("New time after adding 15 hours : " + now.get(Calendar.HOUR_OF_DAY) + ":"+ now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
	}
}

Output

Current Date : 12-23-2017
Current time : 20:36:24
New Date : 12-24-2017
New time after adding 15 hours : 11:36:24





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.