1、获取当前时间(标准时间):
var mydate = new Date();
console.log(mydate); //Fri Aug 24 2018 15:54:44 GMT+0800 (中国标准时间)
2、将时间戳转换为日期格式:
function timestampToTime(timestamp) {
var date = new Date(timestamp * 1000);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
var Y = date.getFullYear() + '-';
var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
var D = date.getDate() + ' ';
var h = date.getHours() + ':';
var m = date.getMinutes() + ':';
var s = date.getSeconds();
return Y+M+D+h+m+s;
}
timestampToTime(1403058804); //"2014-06-18 10:33:24"
3、将日期格式转换为时间戳:
var date = new Date('2014-04-23 18:55:49:123');
// 有三种方式获取
var time1 = date.getTime(); //精确到毫秒
var time2 = date.valueOf(); //精确到毫秒
var time3 = Date.parse(date); //精确到秒,毫秒用000代替
console.log(time1); //1398250549123
console.log(time2); //1398250549123
console.log(time3); //1398250549000
4、JS获取时间戳的方法:
Date.now():返回当前时间距离1970年1月1日0点UTC的毫秒数
Math.round(new Date()/1000):精确到秒级
Date.parse('2019-9-9 19:19:19'):解析一个日期字符串(包含日期和时间),返回从1970年1月1日0点到给定时间的毫秒数
Date.UTC(2019,9,9,19,19,19):同样返回毫秒数,但是参数不是字符串
(new Date()).valueOf():通过valueOf()返回指定对象的原始值
new Date().getTime():通过原型方法获得当前时间的毫秒值
Number(new Date()):将时间转换成number类型的数值
+new Date():相当于调用了valueOf获取时间戳