如何解决日历-时间间隔
| 我有以下Java方法,它根据时间间隔返回String。当间隔为6-14h时,它可以正常工作。private String shiftCount()
{
Calendar time = Calendar.getInstance();
if ((time.get(Calendar.HOUR_OF_DAY) >= 0) && (time.get(Calendar.HOUR_OF_DAY) < 6)) return \"-S1\";
if ((time.get(Calendar.HOUR_OF_DAY) >= 6) && (time.get(Calendar.HOUR_OF_DAY) < 14)) return \"-S2\";
if ((time.get(Calendar.HOUR_OF_DAY) >= 14) && (time.get(Calendar.HOUR_OF_DAY) < 22)) return \"-S3\";
if ((time.get(Calendar.HOUR_OF_DAY) >= 22) && (time.get(Calendar.HOUR_OF_DAY) < 24)) return \"-S1\";
return null;
}
但是如果我需要例如6:10-14:10间隔?
解决方法
您不需要间隔,因为每个区域彼此接触。
private String shiftCount() {
Calendar time = Calendar.getInstance();
// the hours is always >= 0
if (time.get(Calendar.HOUR_OF_DAY) < 6) return \"-S1\";
if (time.get(Calendar.HOUR_OF_DAY) < 14) return \"-S2\";
if (time.get(Calendar.HOUR_OF_DAY) < 22) return \"-S3\";
// the hour is always < 24.
return \"-S1\";
}
或者您可以在一天中使用较长的时间,从而可以使用小时/分钟等的任意组合。
long now = System.currentTimeMillis();
// time of the day in minutes.
long time = ((now + TimeZone.getDefault().getOffset(now)) % 86400000) / 60000;
if (time < 6*60 + 10) return \"-S1\";
if (time < 14*60 + 10) return \"-S2\";
if (time < 22*60) return \"-S3\";
return \"-S1\";
, 您还必须检查MINUTE
字段。
有了joda-time,这将不再那么冗长。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。