比较两个时间(hh:mm:ss)字符串

时间:2011-07-09 04:51:50

标签: javascript

我有hh:mm:ss格式的两个时间字符串。 (例如:12:40:1320:01:01。)如何在JavaScript中比较它们?

6 个答案:

答案 0 :(得分:11)

DEMO HERE

我更喜欢拥有日期对象,但正如其他地方所指出的,如果你想做简单的比较,你可以转换为秒

function dateCompare(time1,time2) {
  var t1 = new Date();
  var parts = time1.split(":");
  t1.setHours(parts[0],parts[1],parts[2],0);
  var t2 = new Date();
  parts = time2.split(":");
  t2.setHours(parts[0],parts[1],parts[2],0);

  // returns 1 if greater, -1 if less and 0 if the same
  if (t1.getTime()>t2.getTime()) return 1;
  if (t1.getTime()<t2.getTime()) return -1;
  return 0;
}

alert(dateCompare("12:40:13","20:01:01"));

秒钟:

function dateDiff(time1,time2) {
  var t1 = new Date();
  var parts = time1.split(":");
  t1.setHours(parts[0],parts[1],parts[2],0);
  var t2 = new Date();
  parts = time2.split(":");
  t2.setHours(parts[0],parts[1],parts[2],0);

  return parseInt(Math.abs(t1.getTime()-t2.getTime())/1000);
}

假设您有24小时和相同的填充,您可以进行简单的字符串比较

 var t1 = "12:40:13", t2= "20:01:01";
 if (t1<t2) {
    console.log(t1," is < ", t2);
 }

答案 1 :(得分:6)

如果“比较”意味着“看看它们是否相等”,并且两者具有相同的格式,为什么不简单:

var time1 = "12:40:13";
var time2 = "20:01:01";

if (time1 == time2) {
    // do stuff
}

如果您需要及时获得差异,转换为日期对象是一种方式(请参阅mplungjan的答案),或者您可以将它们转换为公共单位(比如秒)并减去:

function toSeconds(t) {
    var bits = t.split(':');
    return bits[0]*3600 + bits[1]*60 + bits[2]*1;
}

var secs1 = toSeconds(time1);
var secs2 = toSeconds(time2);

// do stuff  - compare, subtract, less than, greater than, whatever

答案 2 :(得分:1)

以下是我在this website here中修改解决方案的一条建议,希望有所帮助。

function compareTime(time_1, time_2) {
   var s1 = 
       time1.split(":")[0] * 3600 + time1.split(":")[1] * 60 + time1.split(":")[2];
   var s2 = 
       time2.split(":")[0] * 3600 + time2.split(":")[1] * 60 + time1.split(":")[2];
   return Math.abs(s1 - s2); // Gets difference in seconds
}

var time_1 = "12:40:13", time_2 = "20:01:01";
document.write(compareTime(time_1, time_2));

答案 3 :(得分:1)

这是另一个想法:

function compareTimes(timeOne, timeTwo) {           
    if(daterize(timeOne) > daterize(timeTwo)) return 1;
    if(daterize(timeOne) < daterize(timeTwo)) return -1;
    return 0;
}

function daterize(time) {
    return Date.parse("Thu, 01 Jan 1970 " + time + " GMT");
}

您可能还想查看MDN Javascript docs for Dates。 Javascript带有很多陷阱,比如Date.month从0-11开始。

答案 4 :(得分:1)

 Date.parse('01/01/2011 10:20:45') > Date.parse('01/01/2011 5:10:10')

 The 1st January is an arbitrary date, doesn't mean anything.

答案 5 :(得分:0)

var time1 = "09:30";
var time2 = "15:30";

var time1InMinutesForTime1 = getTimeAsNumberOfMinutes(time1);
var time1InMinutesForTime2 = getTimeAsNumberOfMinutes(time2);

var time1IsBeforeTime2 = time1InMinutesForTime1 < time1InMinutesForTime2;

function getTimeAsNumberOfMinutes(time) {
    var timeParts = time.split(":");

    var timeInMinutes = (timeParts[0] * 60) + timeParts[1];

    return Number(timeInMinutes);
}