开发者

Simple, concise way to express "tomorrow at 10:30am" using Java standard libraries

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?


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.


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜