Compare two time (hh:mm:ss) strings

前端 未结 5 1929
半阙折子戏
半阙折子戏 2020-12-11 11:46

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?

5条回答
  •  难免孤独
    2020-12-11 12:33

    If "compare" means "see if they are equal", and the two have the same format, why not simply:

    var time1 = "12:40:13";
    var time2 = "20:01:01";
    
    if (time1 == time2) {
        // do stuff
    }
    

    If you need to get the difference in time, the conversion to a date object is one way (see mplungjan's answer) or you can convert them to a common unit (say seconds) and subtract:

    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
    

提交回复
热议问题