tags:

views:

128

answers:

5

Hi,

I'm trying to add n hours to a Date for a program, but I don't know how I can work with hours. I found on this site a question about this, it was about increamenting a date by a day. I didn't get the whole code, so I don't know how to make it with one hour.

So, how do I make this? I'm guessing I have to somehow use add in calendar.

Thanks!

+11  A: 

Check Calendar class. It has add method (and some others) to allow time manipulation. Something like this should work.

    Calendar cal = Calendar.getInstance(); // creates calendar
    cal.setTime(new Date()); // sets calendar time/date
    cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour
    cal.getTime(); // returns new date object, one hour in the future

Check API for more.

Nikita Rybak
Just be careful if you're dealing with daylight savings/summer time.
CurtainDog
Needless to mention you can add "negative hours"
pramodc84
@CurtainDog Using `Calendar.add()` takes care of that automatically.
Jesper
+1  A: 

If you use Apache Commons / Lang, you can do it in one step using DateUtils.addHours():

Date newDate = DateUtils.addHours(oldDate, 3);

(The original object is unchanged)

seanizer
+5  A: 

With Joda Time

DateTime dt = new DateTime();
DateTime added = dt.plusHours(6);
Babar
+1 a bit unnecessary for this, but if you're going to do more date manipulation, joda time is a great library
Joeri Hendrickx
+1  A: 

Something like:

Date oldDate = new Date(); // oldDate == current time
final long hoursInMillis = 60L * 60L * 1000L;
Date newDate = new Date(oldDate().getTime() + 
                        (2L * hoursInMillis)); // Adds 2 hours
Christopher Hunt
A: 

To simplify @Christopher's example.

Say you have a constant

public static final long HOUR = 3600*1000; // in milli-seconds.

You can write.

Date newDate = new Date(oldDate.getTime() + 2 * HOUR);

If you use long to store date/time instead of the Date object you can do

long newDate = oldDate + 2 * HOUR;
Peter Lawrey