JS時間(日期)比較或相減

來源:互聯網
上載者:User

標籤:java   io   ar   cti   時間   javascript   new   type   

註:此文均來自網上,可行,只供參考

//JAVASCRIPT中 日期相減很麻煩 ,現在有現成的實現方法,拷貝過去就可以用了,方便

//調用該方法(主方法) 
function dateDiff(date1, date2){ 
    var type1 = typeof date1, type2 = typeof date2; 
    if(type1 == ‘string‘) 
    date1 = stringToTime(date1); 
    else if(date1.getTime) 
    date1 = date1.getTime(); 
    if(type2 == ‘string‘) 
    date2 = stringToTime(date2); 
    else if(date2.getTime) 
    date2 = date2.getTime(); 
    return (date1 - date2) / 1000;//結果是秒 
}

//字串轉成Time(dateDiff)所需方法 
function stringToTime(string){ 
    var f = string.split(‘ ‘, 2); 
    var d = (f[0] ? f[0] : ‘‘).split(‘-‘, 3); 
    var t = (f[1] ? f[1] : ‘‘).split(‘:‘, 3); 
    return (new Date( 
    parseInt(d[0], 10) || null, 
    (parseInt(d[1], 10) || 1)-1, 
    parseInt(d[2], 10) || null, 
    parseInt(t[0], 10) || null, 
    parseInt(t[1], 10) || null, 
    parseInt(t[2], 10) || null 
    )).getTime();

}

//調用 dateDiff("2009-10-10 19:00:00","2009-10-10 18:00:00")

返回的是秒鐘

 

 

 

 

//Get days and other datetime
//diffrence two datetime
// date1 :更早的日期 小的日期
// date2 :後面的日期 大的日期
//  返回兩個時間差的天數小時數分數秒數和毫秒數
function DiffLong(datestr1, datestr2) {

    var date1 = new Date(Date.parse(datestr1.replace(/-/g, "/")));
    var date2 = new Date(Date.parse(datestr2.replace(/-/g, "/")));
    var datetimeTemp;
    var isLater = true;

    if (date1.getTime() > date2.getTime()) {
        isLater = false;
        datetimeTemp = date1;
        date1 = date2;
        date2 = datetimeTemp;
    }

    difference = date2.getTime() - date1.getTime();
    thisdays = Math.floor(difference / (1000 * 60 * 60 * 24));

    difference = difference - thisdays * (1000 * 60 * 60 * 24);
    thishours = Math.floor(difference / (1000 * 60 * 60));


    var strRet = thisdays + ‘天‘ + thishours + ‘小時‘;

    return strRet;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.