1

How to subtract an hour from current time-stamp?

Calendar c = Calendar.getInstance();
System.out.println("current: "+c.getTime());
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
kreya
  • 1,091
  • 5
  • 24
  • 52

5 Answers5

8

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.

Sieva Kimajeŭ
  • 337
  • 1
  • 3
  • 12
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

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

http://examples.javacodegeeks.com/core-java/util/calendar/add-subtract-hours-from-date-with-calendar/

Rupesh
  • 2,627
  • 1
  • 28
  • 42
  • when there is already an answer please upvote the other answer if it answers the question instead of giving the same answer. – Thirumalai Parthasarathi Oct 11 '13 at 06:03
  • Please stop worrying about upvote, downvote and extra answers in this post. People are here to help and everybody is trying 100% to help others. Why crib? If you have concerns please reach out to site moderators and they will surely help you out. But please stop making such comments that have no value at all to this post. No offense meant I know your intent is good. – Rupesh Oct 11 '13 at 06:10
  • none taken. But the upvote and downvote buttons are provided for a purpose and i am sure people are trying 100% to help and help indeed should be provided in the right manner. typing-in the same answer again is of no use. i hope you understand what i mean. i know my comment does not add any value to this post but it just expresses the site's policy. – Thirumalai Parthasarathi Oct 11 '13 at 06:34
  • pay a visit [**here**](http://stackoverflow.com/help/deleted-answers) – Thirumalai Parthasarathi Oct 11 '13 at 06:38
1
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, -1);
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
pnathan
  • 713
  • 3
  • 9
0

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);
BBdev
  • 4,898
  • 2
  • 31
  • 45
0

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);
Kedar1442
  • 217
  • 2
  • 8