How to subtract an hour from current time-stamp?
Calendar c = Calendar.getInstance();
System.out.println("current: "+c.getTime());
How to subtract an hour from current time-stamp?
Calendar c = Calendar.getInstance();
System.out.println("current: "+c.getTime());
Add -1
to the Calendar.HOUR
attribute:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR, -1);
Oh! And with Joda Time, there you go:
DateTime date = DateTime.now();
DateTime dateOneHourBack = date.minusHours(1);
Although difference might not be visible here, but it's a much more simple and better API than Date
and Calendar
in JDK.
The answer you are looking for is
cal.add(Calendar.HOUR, -numberOfHours);
where numberOfHours
is the amount you want to subtract.
You can also refer this link for more information
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, -1);
Add -1
add(int field,int amount)
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 1 hours from the current time of the calendar, you can achieve it by calling:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -1);
call add() method with a negative parameter if you want to subtract and positive parameter if you want to add the hour.
for adding 2 hours,
calendar.add(Calendar.Hour,2);
for subtracting 3 hours,
calendar.add(Calendar.Hour,-3);