当前位置:Gxlcms > JavaScript > 时间戳与时间格式互换的实例代码

时间戳与时间格式互换的实例代码

时间:2021-07-01 10:21:17 帮助过:25人阅读

// 时间戳转化为时间
        Date.prototype.format = function(format) {
            var date = {
                "M+": this.getMonth() + 1,
                "d+": this.getDate(),
                "h+": this.getHours(),
                "m+": this.getMinutes(),
                "s+": this.getSeconds(),
                "q+": Math.floor((this.getMonth() + 3) / 3),
                "S+": this.getMilliseconds()
            };
            if (/(y+)/i.test(format)) {
                format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
            }
            for (var k in date) {
                if (new RegExp("(" + k + ")").test(format)) {
                    format = format.replace(RegExp.$1, RegExp.$1.length == 1
                        ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
                }
            }
            return format;
        };

使用:

var effStartDate ="1494565993";//你的时间戳
var date= new Date();
date.setTime(effStartDate);
effStartDate = date.format('yyyy-MM-dd h:m:s'); //转化后的时间

时间转为时间戳:

var stringTime = "2017-06-16 12:21:12";var timestamp2 = Date.parse(new Date(stringTime));
timestamp2 = timestamp2 / 1000; //如果前后端是按照毫秒为单位,那么不用除以1000
console.log(timestamp2);//转化后的时间戳

以上就是时间戳与时间格式互换的实例代码的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行