我想要一些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;
}
但代码无效,因为它总是返回相同的结果。如何测试一次是否在两个其他时间之间?
答案 0 :(得分:3)
阅读javadocs!
if (currentTime.after(schoolTime) && currentTime.before(schoolClosedTime)) {
// school is open
} else {
// school is closed
}
答案 1 :(得分:0)
检查小时是否&lt; 9&amp;&amp;小时> 18: (或其他)
Calendar currentTime = Calendar.getInstance();
int hour = currentTime.get(Calendar.HOUR_OF_DAY);
你只需要一个日历
答案 2 :(得分: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);
}
您也可以使用Calendar
的before()
和after()
。