首页 > 语言 > JavaScript > 正文

JavaScript日期时间与时间戳的转换函数分享

2024-05-06 14:46:28
字体:
来源:转载
供稿:网友

如果只是将当前时间转成时间戳,可以直接使用new Date().getTime()/1000;但如果是将某个具体时间或日期转成Unix时间戳,ie不支持像new Date(“2013-1-1”)  这样带参数的方法,将返回NaN。

对此,我写了以下函数,支持ie6+,谷歌,火狐等浏览器:

代码如下:
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"));

下面这个将时间戳转换成日期格式的函数,支持自定义的日期格式,效果类似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
        W: function(){

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选