JS 获取时间戳 以及将时间戳转化为时间

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25354709/article/details/88424345

一、获得时间戳

//->时间戳
var currenttime = new Date().getTime();
console.log(currenttime);  //->1552381026285

二、将时间戳转化为时间

1、定义一个转化方法

//->格式化时间戳
function dataFormat(num, type) {
	var dd = new Date(num);
	var y = dd.getFullYear();
	var m = dd.getMonth() + 1;
	var d = dd.getDate();
	var h = dd.getHours();
	var i = dd.getMinutes();
	var s = dd.getSeconds();
	m = m < 10 ? '0' + m : m;
	d = d < 10 ? '0' + d : d;
	h = h < 10 ? '0' + h : h;
	i = i < 10 ? '0' + i : i;
	s = s < 10 ? '0' + s : s;
	if(type) {
		return y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s
	} else {
		return y + '-' + m + '-' + d
	}
}

2、转化

//->时间戳
var currenttime = new Date().getTime();
console.log(currenttime);                //->1552381026285
console.log(dataFormat(currenttime, false));  //->2019-03-12

三、后台传过来的字符串1542274800000,怎么把它转换成时间格式

//->放一个自己经常用的代码
Date.prototype.Format = function (fmt) {
    var o = {
            "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+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + ""));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
new Date(1542274800000).Format('yy-MM-dd hh:mm:ss'); //"2018-11-15 17:40:00"

猜你喜欢

转载自blog.csdn.net/qq_25354709/article/details/88424345