【JS】时间格式化

时间格式化yyyy-MM-dd HH:mm:ss 与 yyyy-MM-dd

获取当前时间函数

1
2
3
function mounthShort() {
return new Date();
};

时间格式化函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function dateFormate(dateTime, timeflag) {
const date = new Date(Date.parse(dateTime));
const y = date.getFullYear();
let m = date.getMonth() + 1;
m = m < 10 ? (`0${m}`) : m;
let d = date.getDate();
d = d < 10 ? (`0${d}`) : d;
let h = date.getHours();
h = h < 10 ? (`0${h}`) : h;
let minute = date.getMinutes();
minute = minute < 10 ? (`0${minute}`) : minute;
let seconds = date.getSeconds();
seconds = seconds < 10 ? (`0${seconds}`) : seconds;
let result = '';
if (timeflag) {
result = `${y}-${m}-${d} ${h}:${minute}:${seconds}`;
} else {
result = `${y}-${m}-${d}`;
}
return result;
};

调用并格式化

1
2
3
4
5
var time = mounthShort(); // 返回的值 Wed May 08 2019 09:46:57 GMT+0800 (中国标准时间)
var timeFormat = dateFormate(time,true); // 格式 yyyy-MM-dd HH:mm:ss
var timeFormats = dateFormate(time,false); // 格式 yyyy-MM-dd
console.log(timeFormat); // 2019-05-08 09:46:57
console.log(timeFormats); // 2019-05-08

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function mounthShort() {
return new Date();
};

function dateFormate(dateTime, timeflag) {
const date = new Date(Date.parse(dateTime));
const y = date.getFullYear();
let m = date.getMonth() + 1;
m = m < 10 ? (`0${m}`) : m;
let d = date.getDate();
d = d < 10 ? (`0${d}`) : d;
let h = date.getHours();
h = h < 10 ? (`0${h}`) : h;
let minute = date.getMinutes();
minute = minute < 10 ? (`0${minute}`) : minute;
let seconds = date.getSeconds();
seconds = seconds < 10 ? (`0${seconds}`) : seconds;
let result = '';
if (timeflag) {
result = `${y}-${m}-${d} ${h}:${minute}:${seconds}`;
} else {
result = `${y}-${m}-${d}`;
}
return result;
};

var time = mounthShort(); // 返回的值 Wed May 08 2019 09:46:57 GMT+0800 (中国标准时间)
var timeFormat = dateFormate(time,true); // 格式 yyyy-MM-dd HH:mm:ss
var timeFormats = dateFormate(time,false); // 格式 yyyy-MM-dd
console.log(timeFormat); // 2019-05-08 09:46:57
console.log(timeFormats); // 2019-05-08