DIV CSS 佈局教程網

在 JavaScript 中重現 PHP 的 strtotime() 與 date() 時間戳轉換
編輯:關於JavaScript     

寫過 PHP 的人應該都離不開 strtotime() 與 date():前者把日期字串吃進去吐出 timestamp,後者把 timestamp 格式化成人類看得懂的樣子。JavaScript 沒有這兩個函式,但用原生 Date 就能自己組出來。

日期字串轉時間戳

思路很直接:先把 2012-11-16 10:36:50 這種格式拆解成年、月、日、時、分、秒,再餵給 Date.UTC() 取得毫秒數,最後除以 1000 就是秒級 timestamp。

function datetime_to_unix(datetime) {
  // 把 : 和空白都換成 -,方便統一用 split 切開
  var tmp_datetime = datetime.replace(/:/g, '-');
  tmp_datetime = tmp_datetime.replace(/ /g, '-');
  var arr = tmp_datetime.split("-");

  // 月份要 -1(JS 的 month 從 0 起算),小時 -8 是把 UTC 校正回東八他又
  var now = new Date(Date.UTC(arr[0], arr[1] - 1, arr[2], arr[3] - 8, arr[4], arr[5]));
  return parseInt(now.getTime() / 1000);
}

function unix_to_datetime(unix) {
  var now = new Date(parseInt(unix) * 1000);
  return now.toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}

var datetime = '2012-11-16 10:36:50';
var unix = datetime_to_unix(datetime);
document.write(datetime + ' 轉換後的時間戳為: ' + unix + ' ');

var unix = 1353033300;
var datetime = unix_to_datetime(unix);
document.write(unix + ' 轉換後的日期為: ' + datetime);

這裡的 arr[3] - 8 是為了對齊東八時區的手工偏移。如果專案會跑在不同時區的伺服器上,建議改用 new Date(datetime.replace(/-/g, '/')) 讓瀏覽器依本地時區解析,或統一走 UTC 流程,避免把時區寫死。

只要一個彈出視窗?更精簡的寫法

<script>
function getLocalTime(nS) {
  return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}
alert(getLocalTime(1177824835));
</script>

完整範例:多種格式化方式對照

實務上格式化需求百百種,有人要 2010-10-20 10:00:00,有人只要到分鐘。下面把常見幾種寫法放在一起對照:

<script type="text/javascript">
var day1 = parseInt(new Date().valueOf() / 1000); // 目前時間戳(秒)
var day2 = new Date(day1 * 1000);

// 方法一:正則去掉尾端的秒
function getLocalTime(nS) {
  return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:d{1,2}$/, ' ');
}

// 方法二:直接截字串到 17 個字元
function getLocalTimes(nS) {
  return new Date(parseInt(nS) * 1000).toLocaleString().substr(0, 17);
}

// 方法三:置換年月日為 - 與空白
function getLocalFormatTime(nS) {
  return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}

document.getElementById("btn1").onclick = function () { alert(day1); };
document.getElementById("btn2").onclick = function () { alert(day2.toLocaleString()); };
document.getElementById("btn3").onclick = function () { alert(getLocalTime(day1)); };
document.getElementById("btn4").onclick = function () { alert(getLocalFormatTime(day1)); };

// 方法四:完全不依賴 toLocaleString,自己拼,格式最可控
document.getElementById("btn5").onclick = function () {
  alert(day2.getFullYear() + "-" + (day2.getMonth() + 1) + "-" + day2.getDate() + " "
    + day2.getHours() + ":" + day2.getMinutes() + ":" + day2.getSeconds());
};
</script>

要提醒的是,toLocaleString() 的輸出格式其實由瀏覽器語言設定決定,用正則去「猜」它的樣子並不是最穩健的做法。如果對格式有硬性要求,最後一種逐欄位拼接的方式最可靠;記得補零的話再包一層 ('0' + n).slice(-2) 即可。

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