tags:

views:

337

answers:

4

Dear all,

what is an efficient way to get a certain time for the next day in Java? Let's say I want the long for tomorrow 03:30:00. Setting Calendar fields and Date formatting are obvious. Better or smarter ideas, thanks for sharing them!

Okami

+2  A: 

I'm curious to hear what other people have to say about this one. My own experience is that taking shortcuts (i.e., "better or smarter ideas") with Dates almost always lands you in trouble. Heck, just using java.util.Date is asking for trouble.

Added: Many have recommended Joda Time in other Date-related threads.

Brandon DuRette
Mind giving some examples of why it gets you into trouble.
Anton
Shortcuts almost always ignore the effects of time zone, daylight savings, leap year, leap second, etc. For example, the same time as now tomorrow is not necessarily now + 86400 seconds.
Brandon DuRette
Also, I'll add that bugs relating to the effects of TZ, DST, etc. are the nefarious types of bugs that are easy to slip past the QA department. For proof, consider how in the world java.util.Date made it into Java 1.0 with all it's TZ issues.
Brandon DuRette
A: 

I would consider using the predefined api the smart way to do this.

Paul Whelan
A: 

Not sure why you wouldn't just use the Calendar object? It's easy and maintainable. I agree about not using Date, pretty much everything useful about it is now deprecated. :(

Brian Knoblauch
+4  A: 

I take the brute force approach

Calendar dateCal = Calendar.getInstance();
// make it now
dateCal.setTime(new Date());
// make it tomorrow
dateCal.add(Calendar.DAY_OF_YEAR, 1);
// Now set it to the time you want
dateCal.set(Calendar.HOUR_OF_DAY, hours);
dateCal.set(Calendar.MINUTE, minutes);
dateCal.set(Calendar.SECOND, seconds);
dateCal.set(Calendar.MILLISECOND, 0);
return dateCal.getTime();
Paul Tomblin
dateCal.setTime(new Date()) is redundant. Calendar.getInstance() returns a calendar that is "based on the current time in the default time zone with the default locale".
Brandon DuRette
Thanks, I missed somewhat the add method!
Okami