JS中timestamp的获取与转换

来源:互联网 发布:matlab仿真软件介绍 编辑:程序博客网 时间:2024/06/07 09:58
js不提供直接取unix timestamp的戳记,但是可以用一个简单的语句来实现

var timestamp=Math.round(new Date().getTime()/1000);

 简单解释一下:    new Date() 初始化一个日期时间对象

    get.Time()取毫秒数,所以要取1000

    Math.round是初始化一个数学方法,类似于php的ceil方法。

timestmp转Date:Date.prototype.format = function(format) {
    var o = {
        M+”: this.getMonth() + 1,
        // month
        d+”: this.getDate(),
        // day
        h+”: this.getHours(),
        // hour
        m+”: this.getMinutes(),
        // minute
        s+”: this.getSeconds(),
        // second
        q+”: Math.floor((this.getMonth() + 3) / 3),
        // quarter
        S”: this.getMilliseconds()
        // millisecond
    };
    if (/(y+)/.test(format) || /(Y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + “”).substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp(“(” + k + “)”).test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : (“00 + o[k]).substr((“” + o[k]).length));
        }
    }
    return format;
};

function timestampformat(timestamp) {
    return (new Date(timestamp)).format(“yyyy-MM-dd hh:mm:ss”);
}

原创粉丝点击