gpt4 book ai didi

javascript - 2个日期时间时刻之间的时差

转载 作者:行者123 更新时间:2023-11-30 15:42:22 25 4
gpt4 key购买 nike

所以我有 2 个日期时间对象。

now = Nov 15 4:00 PM
later = Nov 15 6:00PM

我的目标是获取(上午 9 点到下午 5 点)之间的总小时数,给定现在和以后的时间。

结果答案应该是 1 小时。 (因为我只关心上午 9 点到下午 5 点之间的时间范围)

now =  Nov 15 6:00 AM
later = Nov 15 8:00 PM

结果答案应该是 8 小时。

是实现此目的的最佳方法,即使用 moment 中的 diff 函数并剥离小时并计算单个用例(当开始时间小于 9AM/开始时间大于 9AM 时)。同样结束时间(小于下午 5 点/大于 5 点)等?

还有如何解决这种情况,

now = Nov 15 9:00AM
later = Nov 18 2:00PM

结果答案应该是,

8(11 月 15 日)+8(11 月 16 日)+8(11 月 17 日)+5(11 月 18 日)= 29 小时

最佳答案

这是可行的解决方案

var now = moment("15 Nov 2016, 9:00:00 am", "DD MMM yyyy, h:mm:ss a").toDate();
var later = moment("18 Nov 2016, 2:00:00 pm", "DD MMM yyyy, h:mm:ss a").toDate();

function getWorkingHours(now, later) {
var hoursToday = 0;

var workingHourStart = 9;
var workingHourEnd = 17;//5pm
var workDuration = workingHourEnd - workingHourStart;

if(workingHourEnd - getHours(now) > 0) {
hoursToday = (workingHourEnd - getHours(now));
hoursToday = (hoursToday > workDuration) ? workDuration : hoursToday;
}

var hoursLater = 0;

if(getHours(later) - workingHourStart > 0) {
hoursLater = (getHours(later) - workingHourStart);
hoursLater = (hoursLater > workDuration) ? workDuration : hoursLater;
}

var actualDiffHours = (later.getTime() - now.getTime()) / (1000 * 60 * 60);
var actualHoursInBetween = actualDiffHours - (24 - getHours(now)) - getHours(later);

var workingHoursInBetween = (actualHoursInBetween / 24) * 8;

return hoursToday + workingHoursInBetween + hoursLater;
}

function getHours(date) {
var hours = date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600 + date.getMilliseconds() / 3600/1000;
return hours;
}

console.log(getWorkingHours(now, later));
<script src="http://momentjs.com/downloads/moment.min.js"></script>

关于javascript - 2个日期时间时刻之间的时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40619109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com