views:

162

answers:

2

How do you say, add 1 hour to a given result from calendar.getTime?

+4  A: 
Calendar cal = Calendar.getInstance();
//cal.setTime(date); //if you need to pass in a date
cal.add(Calendar.HOUR, 1);
Rich Kroll
+5  A: 

Well, you can add 1000 * 60 * 60 to the millisecond value of the Date. That's probably the simplest way, if you don't want to mutate the Calendar instance itself. (I wouldn't like to guess exactly what Calendar will do around DST changes, by the way. It may well not be adding an hour of UTC time, if you see what I mean.)

So if you do want to go with the Date approach:

date.setTime(date.getTime() + 1000 * 60 * 60);

This will always add an actual hour, regardless of time zones, because a Date instance doesn't have a time zone - it's just a wrapper around a number of milliseconds since midnight on Jan 1st 1970 UTC.

However, I'd strongly advise (as I always do with Java date/time questions) that you use Joda Time instead. It makes this and myriad other tasks a lot easier and more reliable. I know I sound like a broken record on this front, but the very fact that it forces you to think about whether you're actually talking about a local date/time, just a date, a local midnight etc makes a big difference.

Jon Skeet
+1 for DST - incredibly easy to miss, next to impossible to reproduce and fix when it blows up in production 4 months later. BTW, this is the 2nd question I'm seeing today where Jon's answer is not the top one. Is the world as we know it coming to an abrupt end? :-)
ChssPly76
as in depth and as helpful as your answer was, rich needs some noobie love and his answer really was exactly what I needed. Something I should have grabbed from the javadocs but missed :)
jim