1. 程式人生 > >js計算兩個日期差

js計算兩個日期差

function timeDifc(start,end){
    let starts = new Date(start),ends = new Date(end),message = '';
    if (starts.getTime() > ends.getTime())
        return message = "現在的時間小於以前的時間!";

    if ((ends.getTime() - starts.getTime())/(1000*60) < 1)
        return message = "剛剛";

    if (ends.getFullYear() > starts.getFullYear() && ends.getMonth() >= starts.getMonth())
        message += ends.getFullYear() - starts.getFullYear() + "年";

    if (ends.getMonth() > starts.getMonth() && ends.getDate() >= starts.getDate())
        message += ends.getMonth() - starts.getMonth() + "個月";

    if (ends.getDate() > starts.getDate() && ends.getHours() >= starts.getHours())
        message += ends.getDate() - starts.getDate() + "天";

    if (ends.getHours() > starts.getHours() && ends.getMinutes() >= starts.getMinutes())
        message += ends.getHours() - starts.getHours() + "小時";

    if (ends.getMinutes() > starts.getMinutes())
        message += ends.getMinutes() - starts.getMinutes() + "分鐘";

    return message;
};

//  注:上邊的變數是用let宣告的(es6語法),下邊是用babel編譯後的

function timeDifc(start, end) {
    var starts = new Date(start),
        ends = new Date(end),
        message = '';
    if (starts.getTime() > ends.getTime()) return message = "現在的時間小於以前的時間!";

    if ((ends.getTime() - starts.getTime()) / (1000 * 60) < 1) return message = "剛剛";

    if (ends.getFullYear() > starts.getFullYear() && ends.getMonth() >= starts.getMonth()) message += ends.getFullYear() - starts.getFullYear() + "年";

    if (ends.getMonth() > starts.getMonth() && ends.getDate() >= starts.getDate()) message += ends.getMonth() - starts.getMonth() + "個月";

    if (ends.getDate() > starts.getDate() && ends.getHours() >= starts.getHours()) message += ends.getDate() - starts.getDate() + "天";

    if (ends.getHours() > starts.getHours() && ends.getMinutes() >= starts.getMinutes()) message += ends.getHours() - starts.getHours() + "小時";

    if (ends.getMinutes() > starts.getMinutes()) message += ends.getMinutes() - starts.getMinutes() + "分鐘";

    return message;
};


在瀏覽器的console中測試結果如下: