日历 - 时间间隔

问题描述:

我有以下Java方法,它根据时间间隔返回String。当间隔时间如6-14小时时,它工作正常。日历 - 时间间隔

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间隔?

+1

你必须检查小时和分钟的任意组合。 – 2011-06-13 13:21:46

+0

谢谢,我忘了写“使用一些集成功能”或“简单解决方案”;我正在寻找像isInInterval(开始,结束):) – gaffcz 2011-06-13 13:28:30

由于每个区域都接触另一个区域,因此不需要区间。

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"; 
+0

非常好,非常感谢! – gaffcz 2011-06-13 13:48:02

+0

上面的第二个选项将在DST更改天失败 – JodaStephen 2011-06-15 06:43:29

+0

@JodaStephen,第二个示例以与第一个相同的方式处理夏令时更改。即它使用相同的基础方法。 – 2011-06-15 07:08:59

您还必须检查MINUTE字段。

随着乔达时间,这将不太冗长。

+0

谢谢,这就够了,我只需要知道是否存在这种问题的某种功能,像isInInterval(开始,结束):] – gaffcz 2011-06-13 13:30:11

+1

joda-time has '新的时间间隔(开始,结束)' – Bozho 2011-06-13 13:34:02

+0

Jj,谢谢:] – gaffcz 2011-06-13 13:35:14