tags:

views:

92

answers:

2

Using only standard java 1.5 calls, I'm looking for a concise and simple way to get a java Date object for a specific time, say the next 10:30am that occurs in the future. This will generally be tomorrow at 10:30am, but it may be today at 10:30am if the current time is, say, 8am.

Efficiency is only a secondary or tertiary concern.

It seems like there must be a more graceful way to do it than manually constructing a Calendar object and setting each of its fields in a separate method call.

Using SimpleDateFormat would be fine with a format string like "HH:mm", but I don't see a clever way to get it to adjust to the next future 10:30am rather than simply today's 10:30am. Plus, those try/catch blocks are a bit tacky.

Is there really no simple one or two line way to express this?

+5  A: 

There is no convienence method in the standard API, you need a sequence like

Calendar cal = Calendar.getInstance();
Date today = cal.getTime();
cal.set(Calendar.HOUR, 10);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.AM_PM, Calendar.AM);

Date next = cal.getTime();
if (today.after(next)) {
    cal.add(Calendar.DAY_OF_MONTH, 1);
}
System.out.println(cal.getTime());

You should just put this into an utility class.

stacker
Like: `public Date nextDateAt(int hour, int minute );`
OscarRyz
It's not bad certainly. I'm hoping someone can come up with something even more succinct
Mike
+1  A: 

You may also want to look at Joda which provides a better date/time implementation than the JDK, you can get the next 10:30 instance using this code

final LocalDateTime now = new LocalDateTime().withSecondOfMinute(0).withMillisOfDay(0);
final LocalDateTime tenThirty;
if (now.getHourOfDay() <= 10 && now.getMinuteOfHour() <= 30) {
    tenThirty = now.withHourOfDay(10).withMinuteOfHour(30);
} else {
    tenThirty = now.plusDays(1).withHourOfDay(10).withMinuteOfHour(30);
}
Jon Freedman
Yeah, I'm familiar with Joda. But due to space considerations (I'm on android) I would prefer to stick with the standard java library calls.
Mike
Not sure if commons-lang is on your classpath, the `DateUtils` class has useful convinience methods for dealing with `java.util.Date`
Jon Freedman