有两个字符串(开始和结束时间),形式为“16:30”,“02:13”我想比较它们并检查间隔是否大于5分钟。Javascript,Hour Comparisson
如何以简单的方式在Javascript中实现?
有两个字符串(开始和结束时间),形式为“16:30”,“02:13”我想比较它们并检查间隔是否大于5分钟。Javascript,Hour Comparisson
如何以简单的方式在Javascript中实现?
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)
{
}
// 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.");
}
'Date.parse'对于它的输入并不是很聪明,只接受一些预定义的格式。所以试图解析纯时间组件可能会失败,你应该提供一个日期上下文Date.parse(“01/01/2010”+“16:30”)' – Andris 2010-06-18 09:30:09