how to compare two string dates in javascript?

前端 未结 6 1906
暗喜
暗喜 2020-12-03 04:06

I have two string dates in the format of m/d/yyyy. For example, “11/1/2012”, “1/2/2013”. I am writing a function in JavaScript to compare two string dates. The signature of

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 04:43

    You can use "Date.parse()" to properly compare the dates, but since in most of the comments people are trying to split the string and then trying to add up the digits and compare with obviously wrong logic -not completely.

    Here's the trick. If you are breaking the string then compare the parts in nested format.

    Compare year with year, month with month and day with day.

    
    
    var parts1 = "26/07/2020".split('/');
    var parts2 = "26/07/2020".split('/');
    
    var latest = false;
    
    if (parseInt(parts1[2]) > parseInt(parts2[2])) {
        latest = true;
    } else if (parseInt(parts1[2]) == parseInt(parts2[2])) {
        if (parseInt(parts1[1]) > parseInt(parts2[1])) {
            latest = true;
        } else if (parseInt(parts1[1]) == parseInt(parts2[1])) {
            if (parseInt(parts1[0]) >= parseInt(parts2[0])) {
                latest = true;
            } 
        }
    }
    
    return latest;
    
    

提交回复
热议问题