项目中经常会遇到日期和时间的格式化问题,话不多说,直接上代码。
1.日期格式化(yyyy-MM-dd):
function getFormatDate (data) {
let date = new Date(data);
let year = date.getFullYear(); let month = date.getMonth() + 1; let strDate = date.getDate(); if (month >= 1 && month <= 9) { month = '0' + month; } if (strDate >= 0 && strDate <= 9) { strDate = '0' + strDate; } return [year, month, strDate].join('-');
}
2.时间格式化 (yyyy-MM-dd hh:mm:ss):
function getFormatTime (data) {
let date = new Date(data);
let year = date.getFullYear();
let month = date.getMonth() + 1;
let strDate = date.getDate();
let hour = date.getHours(); let minute = date.getMinutes(); let second = date.getSeconds();
if (month >= 1 && month <= 9) {
month = '0' + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = '0' + strDate;
}
if (hour >= 0 && hour <= 9) { hour = '0' + hour; } if (minute >= 0 && minute <= 9) { minute = '0' + minute; } if (second >= 0 && second <= 9) { second = '0' + second; }
return [year, month, strDate].join('-') + ' ' + [hour, minute, second].join(':');
}