Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

javascript - Compare two time (hh:mm:ss) strings

I have two time strings in hh:mm:ss format. (eg: 12:40:13 and 20:01:01.) How can I compare these in JavaScript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

DEMO HERE

I prefer to have date objects, but as pointed out elsewhere, you can just convert to seconds if you want to do simple compares

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"));

For seconds:

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);
}

Assuming you have 24 hour times and same padding you can do simple string compare

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...