export function formatDigit(n) {
return n.toString().replace(/^(\d)$/, '0$1');
}
export const formatDate = (timestamp, formats) => {
formats = formats || 'Y-M-D';
var myDate = undefined;
if (timestamp) {
if (typeof(timestamp) != 'string') {
myDate = timestamp;
} else {
myDate = new Date(timestamp);
}
} else {
myDate = new Date();
}
var year = myDate.getFullYear();
var month = formatDigit(myDate.getMonth() + 1);
var day = formatDigit(myDate.getDate());
var hour = formatDigit(myDate.getHours());
var minute = formatDigit(myDate.getMinutes());
var second = formatDigit(myDate.getSeconds());
return formats.replace(/Y|M|D|h|m|s/g, (matches) => {
return {
Y: year,
M: month,
D: day,
h: hour,
m: minute,
s: second
} [matches];
});
}
console.log(formatDate(new Date(),'Y-M-D h:m:s')); 结果:2021-12-15 09:57:36