tags:

views:

110

answers:

5

What is the correct way to increment a java.util.Date by one day.

I'm thinking something like

        Calendar cal = Calendar.getInstance();
        cal.setTime(toDate);
        cal.add(Calendar.DATE, 1);
        toDate = cal.getTime();

It doesn't 'feel' right.

+6  A: 

That would work.

It doesn't 'feel' right.

If it is the verbosity that bothers you, welcome to the Java date-time API :-)

Thilo
+5  A: 

Yeah, that's right. Java Date APIs feel wrong quite often. I recommend you try Joda Time. It would be something like:

DateTime startDate = ...
DateTime endDate = startDate.plusDays(1);

or:

Instant start = ...
Instant end = start.plus(Days.days(1).toStandardDuration());
Matthew Flaschen
+1 for the sentiment
Thilo
Absolutely! I dislike date arithmetic in java.util.Date so much that on my current I isolated it into a set of 6-8 methods. This was fine, but after I found Joda Time these methods became 1-2 liners *and* a couple even gained a bit in generality.
Jim Ferrans
+1  A: 

I believe joda time library makes it much more clean to work with dates.

Alfred
A: 

Here's how I do it:

Date someDate = new Date(); // Or whatever    
Date dayAfter = new Date(someDate.getTime()+(24*60*60*1000));

Where the math at the end converts a day's worth of seconds to milliseconds.

Tony Ennis
Why the -1? The number of hours, minutes, and seconds is unlikely to change anytime soon.
Tony Ennis
for one thing, this doesn't take into account Calendar things like leap year and leap seconds and other minutia, this is why the equivilent methods on Date() are deprecated and Calendar, and GregorianCalendar exist in the first place. And your code doesn't handle daylight savings time either, naive at best, a source of endless thedailyWTF articles and bugs at worst.
fuzzy lollipop
A: 

If you do not like the math in the solution from Tony Ennis

Date someDate = new Date(); // Or whatever
Date dayAfter = new Date(someDate.getTime() + TimeUnit.DAYS.toMillis( 1 ));
Ivin