How do you say, add 1 hour to a given result from calendar.getTime?
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.
Calendar cal = Calendar.getInstance();
//cal.setTime(date); //if you need to pass in a date
cal.add(Calendar.HOUR, 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With