【发布时间】:2010-06-18 09:07:43
【问题描述】:
有两个字符串(开始时间和结束时间),格式为“16:30”、“02:13”,我想比较它们并检查间隔是否大于 5 分钟。
如何在 Javascript 中以简单的方式实现这一点?
【问题讨论】:
标签: javascript datetime time
有两个字符串(开始时间和结束时间),格式为“16:30”、“02:13”,我想比较它们并检查间隔是否大于 5 分钟。
如何在 Javascript 中以简单的方式实现这一点?
【问题讨论】:
标签: javascript datetime time
function parseTime(time) {
var timeArray = time.split(/:/);
// Using Jan 1st, 2010 as a "base date". Any other date should work.
return new Date(2010, 0, 1, +timeArray[0], +timeArray[1], 0);
}
var diff = Math.abs(parseTime("16:30").getTime() - parseTime("02:13").getTime());
if (diff > 5 * 60 * 1000) { // Difference is in milliseconds
alert("More that 5 mins.");
}
你需要在午夜结束吗?那么这个就更难了。例如,23:59 和 00:01 将产生 23 小时 58 分钟而不是 2 分钟的差异。
如果是这种情况,您需要更仔细地定义您的情况。
【讨论】:
你可以这样做:
if (((Date.parse("16:30") - Date.parse("02:13")) / 1000 / 60) > 5)
{
}
【讨论】:
Date.parse 对它获取的输入不是很聪明,并且只接受一些预定义的格式。因此,尝试解析纯时间组件可能会失败,您也应该提供日期上下文 Date.parse("01/01/2010 "+"16:30")
// time is a string having format "hh:mm"
function Time(time) {
var args = time.split(":");
var hours = args[0], minutes = args[1];
this.milliseconds = ((hours * 3600) + (minutes * 60)) * 1000;
}
Time.prototype.valueOf = function() {
return this.milliseconds;
}
// converts the given minutes to milliseconds
Number.prototype.minutes = function() {
return this * (1000 * 60);
}
减去时间会强制对象通过调用以毫秒为单位返回给定时间的valueOf 方法来评估它的值。 minutes 方法是将给定的分钟数转换为毫秒的另一种便捷方法,因此我们可以将其用作整个比较的基础。
new Time('16:30') - new Time('16:24') > (5).minutes() // true
【讨论】:
这包括检查午夜是否在两次之间(根据您的示例)。
var startTime = "16:30", endTime = "02:13";
var parsedStartTime = Date.parse("2010/1/1 " + startTime),
parsedEndTime = Date.parse("2010/1/1 " + endTime);
// if end date is parsed as smaller than start date, parse as the next day,
// to pick up on running over midnight
if ( parsedEndTime < parsedStartTime ) ed = Date.parse("2010/1/2 " + endTime);
var differenceInMinutes = ((parsedEndTime - parsedStartTime) / 60 / 1000);
if ( differenceInMinutes > 5 ) {
alert("More than 5 mins.");
}
【讨论】: