DIV CSS 佈局教程網

JavaScript 日期與 Unix 時間戳雙向轉換函數(相容 IE6+)
編輯:關於JavaScript     

如果只要拿當前時間的時間戳,一行 new Date().getTime()/1000 就搞定。但只要想把「某個具體日期字串」轉成 Unix 時間戳,就會踢到鐵板:IE 不支援 new Date("2013-1-1") 這種帶參數的寫法,直接丟回 NaN。

一、日期字串轉時間戳

繞過這個問題的方式是自己用正則表達式把字串拆開,再交給多參數版本的 Date 建構式。以下寫法在 IE6+、Chrome、Firefox 都能正常運作:

復制代碼 代碼如下:

function getTime(day){
  re = /(\d{4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:\s+(\d{1,2}):(\d{1,2}):(\d{1,2}))?/.exec(day);
  return new Date(re[1],(re[2]||1)-1,re[3]||1,re[4]||0,re[5]||0,re[6]||0).getTime()/1000;
}

//test
alert(getTime("2013-02-03 10:10:10"));
alert(getTime("2013-02-03"));
alert(getTime("2013-02"));
alert(getTime("2013"));

正則裡的每一段都是選填的,所以只給年份、只給年月都能正確處理;月份要減 1 是因為 JavaScript 的月份從 0 起算。

二、時間戳轉格式化日期

反方向的轉換參考了 PHP 的 date() 設計,支援自訂格式字元,同樣相容 IE6+ 到各家現代瀏覽器。這個版本是網友實作的,之後有時間我也想自己重寫一份。

復制代碼 代碼如下:

function date(format, timestamp){
    var a, jsdate=((timestamp) ? new Date(timestamp*1000) : new Date());
    var pad = function(n, c){
        if((n = n + "").length < c){
            return new Array(++c - n.length).join("0") + n;
        } else {
            return n;
        }
    };
    var txt_weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var txt_ordin = {1:"st", 2:"nd", 3:"rd", 21:"st", 22:"nd", 23:"rd", 31:"st"};
    var txt_months = ["", "January", "February", "March", "April", "May", "June", "July",
                      "August", "September", "October", "November", "December"];
    var f = {
      // Day
      d: function(){return pad(f.j(), 2)},
      D: function(){return f.l().substr(0,3)},
      j: function(){return jsdate.getDate()},
      l: function(){return txt_weekdays[f.w()]},
      N: function(){return f.w() + 1},
      S: function(){return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th'},
      w: function(){return jsdate.getDay()},
      z: function(){return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0},
      // Week:計算 ISO 週數
      W: function(){
          var a = f.z(), b = 364 + f.L() - a;
          var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
          if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
              return 1;
          } else{
              if(a <= 2 && nd >= 4 && a >= (6 - nd)){
                  nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                  return date("W", Math.round(nd2.getTime()/1000));
              } else{
                  return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
              }
          }
      },
      // Month
      F: function(){return txt_months[f.n()]},
      m: function(){return pad(f.n(), 2)},
      M: function(){return f.F().substr(0,3)},
      n: function(){return jsdate.getMonth() + 1},
      t: function(){
          var n;
          if( (n = jsdate.getMonth() + 1) == 2 ){
              return 28 + f.L();
          } else{
              if( n & 1 && n < 8 || !(n & 1) && n > 7 ){ return 31; }
              else{ return 30; }
          }
      },
      // Year
      L: function(){var y = f.Y();return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0},
      Y: function(){return jsdate.getFullYear()},
      y: function(){return (jsdate.getFullYear() + "").slice(2)},
      // Time
      a: function(){return jsdate.getHours() > 11 ? "pm" : "am"},
      A: function(){return f.a().toUpperCase()},
      g: function(){return jsdate.getHours() % 12 || 12},
      G: function(){return jsdate.getHours()},
      h: function(){return pad(f.g(), 2)},
      H: function(){return pad(jsdate.getHours(), 2)},
      i: function(){return pad(jsdate.getMinutes(), 2)},
      s: function(){return pad(jsdate.getSeconds(), 2)},
      // Timezone
      O: function(){
          var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
          if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
          return t;
      },
      P: function(){var O = f.O();return (O.substr(0, 3) + ":" + O.substr(3, 2))},
      // Full Date/Time
      c: function(){return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P()},
      U: function(){return Math.round(jsdate.getTime()/1000)}
    };

    return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
        if( t != s ){
            ret = s;          // 被跳脫
        } else if( f[s] ){
            ret = f[s]();     // 有對應的日期函式
        } else{
            ret = s;          // 一般字元
        }
        return ret;
    });
}

//test
alert(date('Y-m-d H:i:s',(new Date).getTime()/1000));
alert(date('Y-m-d',(new Date).getTime()/1000));
alert(date('Y-m-d H:i:s','1355252653'));

它的運作方式是把所有格式字元對應到 f 物件裡的函式,再用一次 replace 掃過格式字串逐一替換;前面加上反斜線就能跳脫,讓該字元原樣輸出。另外 B(Swatch 網路時間)、o、u、e、I、T、Z 等少用格式尚未實作。

這兩個函式搭起來,前後端資料交換時的時間格式問題基本都能應付。

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