gpt4 book ai didi

javascript - 计算时差|字符串

转载 作者:行者123 更新时间:2023-12-03 05:36:14 25 4
gpt4 key购买 nike

我想显示计划时间和预期时间之间的分钟数。

这不是比较,这是计算预定时间和预期时间在不同时间有多少分钟。

由于两次都显示为字符串,是否需要将字符串转换为数字然后进行比较?

我想要返回的只是时间差的数字。

这是我的对象:

{
station: "Macclesfield",
scheduled: "15:41",
expected: "15:50",
platform: "1"
}

最佳答案

var data = {
station: "Macclesfield",
scheduled: "15:41",
expected: "15:50",
platform: "1"
}

function getTimeDifference(scheduled, expected) {
scheduled = scheduled.split(':'); //get array [hours, minutes]
expected = expected.split(':');
var hours = expected[0] - scheduled[0]; //difference in hours
var minutes = expected[1] - scheduled[1]; //difference in minutes
if (minutes < 0) { //if minutes are negative we know it wasn't a full hour so..
hours--; //subtract an hour
minutes += 60; //add 60 minutes
} //now we're ok
if (hours) //if hours has a value
return hours + ':' + minutes;
return minutes; //hours is 0 so we only need the minutes
}

console.log(getTimeDifference(data.scheduled, data.expected));

data.expected = "16:00";

console.log(getTimeDifference(data.scheduled, data.expected));

data.expected = "17:00";

console.log(getTimeDifference(data.scheduled, data.expected));

关于javascript - 计算时差|字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40726842/

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