1、日期语法:
//获取当前时间
var time = new Date(); //Sat May 08 2021 21:47:16 GMT+0800
(中国标准时间)
//设置时间--传参是时间戳--一定要13位
var time0 = new Date(1620398318000); //Fri May 07 2021 22:38:38 GMT+0800 (中国标准时间)
//设置时间--传参是时间日期字符串
var time = new Date('2015-03-19 12:00:00'); //Thu Mar 19 2015 12:00:00 GMT+0800 (中国标准时间)
var time2 = new Date('2015/03/19 12:00:00'); //Thu Mar 19 2015 12:00:00 GMT+0800 (中国标准时间) 如果把时分秒变成这样12/00/00就是错误的
//将当前时间转成时间戳
let time3 = new Date().getTime(); //1620398150466, 精确到毫秒 (13位数字)
let time4 = new Date().valueOf(); //1620398318185.精确到毫秒 (13位数字)
let time5 = Date.now(); //1603009495724,精确到毫秒,实际上是new Date().getTime()
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
let time6 = Date.parse(new Date()); //1620398318000,精确到秒--10位数---如果加后面3个0后变成毫秒) 不推荐
2、时间戳转成时间格式1—(年、月、日、时、分、秒)
1)时间格式--年、月、日、时、分、秒
function change(d){
return d<10?'0'+d:d
}
function date(){
var date = new Date(时间戳);
var y = date.getFullYear();
var m = change(date.getMonth()+1); //js从0开始取
var d = change(date.getDate());
var h = change(date.getHours());
var mm = changedate.getMinutes());
var s= change(date.getSeconds());
console.log(date+" | "+y+"年"+m+"月"+d+"日"+h+"时"+mm+"分"+s+"秒" );
结果:Mon Jun 15 15:44:50 UTC+0800 2021 (中国标准时间) | 2021年4月15日15时44分50秒
}
2) 时间格式: 2019-03-19 12:00:00
var formatDateTime = function () {
var date = new Date(时间戳);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
var d = date.getDate();
d = d < 10 ? ('0' + d) : d;
var h = date.getHours();
h = h < 10 ? ('0' + h) : h;
var mm = date.getMinutes();
mm = mm < 10 ? ('0' + mm) : mm;
var s= date.getSeconds();
s = s < 10 ? ('0' + s) : s;
return y + '-' + m + '-' + d+' '+h+':'+mm+':'+s
};
3、时间戳转时间格式(参数—1、时间戳,2、yyyy-mm-dd)
Date.prototype.formatDate = function(date,format){
}