Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(new Date()); // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour
cal.getTime(); // returns new date object plus one hour
Date oldDate = new Date(); // oldDate == current time
final long hoursInMillis = 60L * 60L * 1000L;
Date newDate = new Date(oldDate().getTime() +
(2L * hoursInMillis)); // Adds 2 hours
String myString = "09:00 12/12/2014";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm dd/MM/yyyy");
Date myDateTime = null;
//Parse your string to SimpleDateFormat
try
{
myDateTime = simpleDateFormat.parse(myString);
}
catch (ParseException e)
{
e.printStackTrace();
}
System.out.println("This is the Actual Date:"+myDateTime);
Calendar cal = new GregorianCalendar();
cal.setTime(myDateTime);
//Adding 21 Hours to your Date
cal.add(Calendar.HOUR_OF_DAY, 21);
System.out.println("This is Hours Added Date:"+cal.getTime());
输出如下:
This is the Actual Date:Fri Dec 12 09:00:00 EST 2014
This is Hours Added Date:Sat Dec 13 06:00:00 EST 2014
Date argDate = new Date(); //set your date.
String argTime = "09:00"; //9 AM - 24 hour format :- Set your time.
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
String dateTime = sdf.format(argDate) + " " + argTime;
Date requiredDate = dateFormat.parse(dateTime);
myJavaUtilDate.toInstant() // Convert from legacy class to modern class, an `Instant`, a point on the timeline in UTC with resolution of nanoseconds.
.plus( // Do the math, adding a span of time to our moment, our `Instant`.
Duration.ofHours( 8 ) // Specify a span of time unattached to the timeline.
) // Returns another `Instant`. Using immutable objects creates a new instance while leaving the original intact.
public static String getCurrentDatetimePlusNoOfHours(int numberOfHours) {
String futureDay = getCurrentDatetime(); // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(futureDay));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.HOUR, numberOfHours); // number of hours to add, if it's minus send - value like -4
futureDay = sdf.format(c.getTime()); // dt is now the new date
return futureDay;
}
Call the method
getCurrentDatetimePlusNoOfHours(4));