日历-时间间隔

问题描述

| 我有以下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,这将不再那么冗长。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...