0

我想要一些 Java 代码,它会根据当前时间告诉我学校何时开放。

当我在上午 9 点到下午 6 点之间调用此方法时,它应该返回“学校开放”,否则它应该在下午 6 点之后和上午 9 点之前返回“学校关闭”。

public Calendar shopStartTime(String msg)
{
    Calendar currentTime = Calendar.getInstance();
    Calendar schoolTime = Calendar.getInstance();
    Calendar schoolClosedTime = Calendar.getInstance();
    schoolTime.set(Calendar.HOUR_OF_DAY, 9);
    schoolTime.set(Calendar.MINUTE, 0);
    schoolTime.set(Calendar.SECOND, 0);
    schoolTime.set(Calendar.MILLISECOND, 0);
    schoolClosedTime.set(Calendar.HOUR_OF_DAY, 18);
    schoolClosedTime.set(Calendar.MINUTE, 0);
    schoolClosedTime.set(Calendar.SECOND, 0);
    schoolClosedTime.set(Calendar.MILLISECOND, 0);
    if (schoolTime.compareTo(currentTime) <= 0 && 
       (currentTime.compareTo(schoolClosedTime)>=0))
    {
        // check for time
        Toast.makeText(getSherlockActivity(), "school is closed ", 
            Toast.LENGTH_SHORT).show();
    }
    else 
    {
        Toast.makeText(getSherlockActivity(), " school is open", 
            Toast.LENGTH_SHORT).show();
    }
    return currentTime;
}

但是代码不起作用,因为它总是返回相同的结果。我如何测试一个时间是否在一天中的另外两个时间之间?

4

3 回答 3

3

阅读javadocs!

if (currentTime.after(schoolTime) && currentTime.before(schoolClosedTime)) {
    // school is open
} else {
    // school is closed
}
于 2013-08-03T16:46:27.223 回答
0

检查小时 <9 && 小时 >18: (或其他)

Calendar currentTime = Calendar.getInstance();
int hour  = currentTime.get(Calendar.HOUR_OF_DAY);

你只需要一个日历

于 2013-08-03T16:45:45.847 回答
0

除了Calendar您使用过的之外,另一种简单的方法是:

private boolean inRange(Date now) throws ParseException {
    final Date start = new SimpleDateFormat("HH.mm.ss").parse("09.00.00");
    final Date end = new SimpleDateFormat("HH.mm.ss").parse("18.00.00");
    return now.after(start)&& now.before(end);
}

您也可以使用before()after()Calendar

于 2013-08-03T16:48:01.817 回答