DIV CSS 佈局教程網

時間格式與時間戳互轉:JavaScript 實作整理
編輯:JavaScript綜合知識     

後端給的時間戳是秒數,前端要顯示成日期字串;表單填回來的日期字串,又要轉成時間戳送回去。這兩個方向各寫一個函式就搞定了。

一、日期字串轉時間戳

function transdate(endTime) {
    var date = new Date();
    date.setFullYear(endTime.substring(0, 4));
    date.setMonth(endTime.substring(5, 7) - 1);
    date.setDate(endTime.substring(8, 10));
    date.setHours(endTime.substring(11, 13));
    date.setMinutes(endTime.substring(14, 16));
    date.setSeconds(endTime.substring(17, 19));
    return Date.parse(date) / 1000;
}

兩個重點:月份要減 1,因為 setMonth 的參數是從 0 開始;最後除以 1000,因為 JavaScript 的時間戳以毫秒計,而多數後端語言用的是秒。

二、時間戳轉日期字串

轉成 2011-3-16 16:50:43 格式:

function getDate(tm) {
    return new Date(parseInt(tm) * 1000).toLocaleString()
        .replace(/年|月/g, "-").replace(/日/g, " ");
}

這裡反过来要乘以 1000,把秒還原成毫秒才能建構正確的 Date。

要中文格式 2011年3月16日 16:50:43,直接用 toLocaleString 即可:

function getDate(tm) {
    return new Date(parseInt(tm) * 1000).toLocaleString();
}

只要到分鐘 2011年3月16日 16:50,用 substr 截斷:

function getDate(tm) {
    return new Date(parseInt(tm) * 1000).toLocaleString().substr(0, 16);
}

提醒

toLocaleString() 的輸出格式依瀏覽器與作業系統地區設定而異,用固定位置 substr 或字串替換去解析,在不同環境下可能對不對齊。若專案對格式有嚴格要求,建議改用 getFullYear()、getMonth() 等 getter 自己組字串,結果才會穩定一致。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved