我需要获得两个日期之间的秒数,并且仅在工作时间(ex 0800-1600)。 有关如何在Java中执行此操作的任何建议吗?
long seconds = ((datenow.getTime() - datethen.getTime()) / 1000);
答案 0 :(得分:1)
您可以使用以下内容:
public static void main(String[] args) {
Calendar cal1 = Calendar.getInstance();
cal1.set(2011, 10, 10, 12, 00, 00);
Date datenow = cal1.getTime();
Calendar cal2 = Calendar.getInstance();
cal2.set(2011, 10, 14, 15, 00, 00);
Date datethen = cal2.getTime();
// check for weekends
long daynow = TimeUnit.MILLISECONDS.toDays(datenow.getTime());
long daythen = TimeUnit.MILLISECONDS.toDays(datethen.getTime());
long daydiff = daythen - daynow;
long weekenddiff = daydiff / 7; // number of weekends
if (cal1.get(Calendar.DAY_OF_WEEK) > cal2.get(Calendar.DAY_OF_WEEK)) {
weekenddiff++;// we have a weekend but not another full week;
}
long secDiff = TimeUnit.SECONDS.convert(16, TimeUnit.HOURS);
long weekendAdditionalSecDiff = TimeUnit.SECONDS.convert(16, TimeUnit.HOURS); // 16 additional hours for the weekend
// 16 non-work hours between two shifts
daydiff *= secDiff;
daydiff += (weekenddiff * weekendAdditionalSecDiff);
long workDiffSeconds = TimeUnit.SECONDS.convert(
datethen.getTime() - datenow.getTime(),
TimeUnit.MILLISECONDS) - daydiff;
System.out.println("Difference in working hours is "
+ workDiffSeconds + " seconds");
System.out.println("Difference in working hours is "
+ TimeUnit.HOURS.convert(workDiffSeconds, TimeUnit.SECONDS) + " hours");
}
首先计算你的日子之间的天数,然后从实际差异中减去非工作时间秒数。
对于周末,每天额外增加8个非工作时间。
答案 1 :(得分:0)
当我这样做时,我发现最简单的选择两个日期,开始和结束。
然后在几秒钟内表达。
然后通过获取每个日期的mod和86400(每天秒数)来查找每个日期的午夜。
然后从那里很简单。关键是要在午夜找到间隔的终点。
答案 2 :(得分:0)