计算两个日期之间的小时数,不包括周末 [英] Calculate number of hours between two dates not including weekends

查看:156
本文介绍了计算两个日期之间的小时数,不包括周末的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我在尝试计算24小时中在Java中两个不同时间戳之间(不包括周末)之间发生的小时数时遇到问题。

Hello i am having issue trying to calculate the amount of hours in a 24 hour day that took place between two different timestamps in java not including weekends.

String timestamp = rs.getString("timestamp");

 String timeStamp = new SimpleDateFormat("yyyyMMddHH").format(new Date());

   int currentTimeStamp = Integer.parseInt(timeStamp);

   String orderTime = timestamp.replace("-", "");
   String[] splitTimestamp = orderTime.split(" ");

   String finalTimestamp = splitTimestamp[0] +    splitTimestamp[1].substring(0,2);

   int orderTimeStamp = Integer.parseInt(finalTimestamp);

此功能目前可以正常工作,但包括周末。

This currently does work but it includes weekends.

如果有人能帮助我,我将非常感激。

If anyone could help me out I would be very grateful.

这一切都在东部时区完成。

This is all done Eastern time zone. Holidays aren't required or needed just weekends.

推荐答案

我发现使用java.util.Calendar可以使其更清洁,这是一个示例从3月1日(上午8点)到当前时间的小时数:

I find it cleaner with java.util.Calendar, here is an example getting number of hours since March 1st (8am) until current time :

final Calendar first = new Calendar.Builder()
        .setDate(2016, 2, 1).set(Calendar.AM_PM, 0).set(Calendar.HOUR, 8).build();
final Calendar second = Calendar.getInstance();

int numberOfDays = 0;
long numberOfHours = 0;
//Get number of full days
while(first.get(Calendar.DATE) != second.get(Calendar.DATE)){
    if(Calendar.SATURDAY != first.get(Calendar.DAY_OF_WEEK)
            && Calendar.SUNDAY != first.get(Calendar.DAY_OF_WEEK)){
        numberOfDays++;
    }
    first.roll(Calendar.DATE, true);
}
//Get number of hours in the remaining day
numberOfHours = TimeUnit.MILLISECONDS
        .toHours(second.getTimeInMillis() - first.getTimeInMillis());

System.out.println("Difference = " + 
        ( numberOfDays * 24 + numberOfHours ) + " hour(s)");

这篇关于计算两个日期之间的小时数,不包括周末的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆