想通过javascript获取当前时间并格式化为:YYYY-MM-DD HH:ii:ss
toISOString方式
可使用 toISOString()
获取当前时间,但是转换因为时区问题会相差8小时。
1
|
new Date(). toISOString()
|
解决时区问题:
1
2
|
const date = new Date(+new Date() + 8 * 3600 * 1000);
const isoDate = date. toISOString();
|
isoDate
包含Z和毫秒等信息,再次格式化
1
|
const myDate = isoDate.toISOString().slice(0, 19).replace('T', ' ');
|
原型Date方式
需要自己组装,灵活性强,代码较冗长,可封闭为方法调用。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
let year=new Date().getFullYear();//年
if (year< 1900) year = year + 1900;
let month = new Date().getMonth() + 1;//月
if (month < 10) month = '0' + month;
let day = new Date().getDate();//日
if (day < 10) day = '0' + day;
let hour = new Date().getHours();//小时
if (hour < 10) hour = '0' + hour;
let minute = new Date().getMinutes();//分钟
if (minute < 10) minute = '0' + minute;
let second = new Date().getSeconds();//秒
if (second < 10) second = '0' + second;
const myDate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
|