javascript获取各种格式字日期字符串
/**
* 获取各种格式字符串
* 格式 YYYY-MM-DD HH:mm
* @param {*} date
* @param {*} format
*/
export function getDate(date, format) {
let curDate = date
let dateString = ''
if (!curDate) {
curDate = new Date()
} else {
// ie11下需将-替换成/,否则报错
if (typeof (date) === 'string' && date.indexOf('-') !== -1) {
date = date.replace(/-/g, '/')
}
curDate = new Date(date)
}
if (format === 'YYYY') {
dateString = curDate.getFullYear()
}
if (format === 'YYYY-MM') {
dateString = curDate.getFullYear() + '-' + (curDate.getMonth() + 1 < 10 ? '0' + (curDate.getMonth() + 1) : curDate.getMonth() + 1)
}
if (format === 'YYYY-MM-DD') {
dateString = curDate.getFullYear() + '-' + (curDate.getMonth() + 1 < 10 ? '0' + (curDate.getMonth() + 1) : curDate.getMonth() + 1) + '-' + (curDate.getDate() < 10 ? '0' + curDate.getDate() : curDate.getDate())
}
if (format === 'YYYY-MM-DD HH:mm') {
dateString = curDate.getFullYear() + '-' + (curDate.getMonth() + 1 < 10 ? '0' + (curDate.getMonth() + 1) : curDate.getMonth() + 1) + '-' + curDate.getDate() + ' ' + (curDate.getHours() < 10 ? '0' + curDate.getHours() : curDate.getHours()) + ':' + (curDate.getMinutes() < 10 ? '0' + curDate.getMinutes() : curDate.getMinutes())
}
if (format === 'HH:mm') {
dateString = curDate.getHours() + ':' + (curDate.getMinutes() < 10 ? '0' + curDate.getMinutes() : curDate.getMinutes())
}
return dateString
}
调用的时候传入时间和格式,兼容ie,目前了解到ie11不能正常解析横杠,所以需要先处理成斜杠
getDate(date, "YYYY-MM-DD")
发表评论 (审核通过后显示评论):