Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding java time objects

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

like image 625
Louis Avatar asked Dec 14 '22 03:12

Louis


2 Answers

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.

like image 142
Jon Skeet Avatar answered Dec 15 '22 17:12

Jon Skeet


Calendar cal = Calendar.getInstance();
//cal.setTime(date); //if you need to pass in a date
cal.add(Calendar.HOUR, 1);
like image 27
Rich Kroll Avatar answered Dec 15 '22 16:12

Rich Kroll