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

Java Date and Time Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.