/**
* 获取年月日 时分秒
* @param {string | number} time 时间字符串 | 时间戳
* @returns { year, month, date, hours, minutes, seconds }
*/
function getDate (time) {
const date = new Date(time)
const y = date.getFullYear()
const M = date.getMonth() + 1
const MM = M > 9 ? M : '0' + M
const d = date.getDate()
const dd = d > 9 ? d : '0' + d
const H = date.getHours()
const HH = H > 9 ? H : '0' + H
const m = date.getMinutes()
const mm = m > 9 ? m : '0' + m
const s = date.getSeconds()
const ss = s > 9 ? s : '0' + s
const t = date.toLocaleTimeString()
const t_1 = t.substr(0, 2)
const t_2 = t.slice(2)
const h = t_2.split(':')[0]
const hh = h > 9 ? h : '0' + h
const a_p = t_1 === '上午' ? 'am' : 'pm'
return { y, M, MM, d, dd, H, HH, m, mm, s, ss, h, hh, a_p }
}
/**
* 格式化时间类型
* @param {string | number} time 时间字符串 | 时间戳
* @param {string} type 时间格式
* @returns 格式化后时间字符串
*/
function format (time, type) {
if(time !== null && !time)
throw('format error: params 1 time is required')
if(new Date(time) == 'Invalid Date')
throw('time error: params 1 time is Invalid Date')
if(type && typeof type !== 'string')
throw('format error: params 2 type not is a string')
const { y, M, MM, d, dd, H, HH, m, mm, s, ss, h, hh, a_p } = getDate(time)
switch(type) {
case 'yyyy-MM-dd':
return [y, MM, dd].join('-')
case 'yyyy-M-d':
return [y, M, d].join('-')
case 'HH:mm:ss':
return [HH, mm, ss].join(':')
case 'H:m:s':
return [H, m, s].join(':')
case 'h:m:s':
return [h, m, s].join(':') + ' ' + a_p
case 'yyyy-MM-dd HH:mm:ss':
return [y, MM, dd].join('-') + ' ' + [HH, mm, ss].join(':')
case 'yyyy-M-d H:m:s':
return [y, M, d].join('-') + ' ' + [H, m, s].join(':')
default:
return [y, MM, dd].join('-')
}
}
使用
console.log(format(new Date())) // 2021-06-09
console.log(format(null)) // 1970-01-01
console.log(format(new Date(), 'yyyy-M-d')) // 2021-6-9
console.log(format(new Date(), 'HH:mm:ss')) // 10:17:46
console.log(format(new Date(), 'h:m:s')) // 10:17:46 am
console.log(format(new Date(), 'yyyy-MM-dd HH:mm:ss')) // 2021-06-09 10:17:46
console.log(format(new Date(), 'yyyy-M-d h:m:s')) // 2021-06-09
console.log(format(undefined)) // Uncaught format error: params 1 time is required
console.log(format(new Date(), 22)) // Uncaught format error: params 2 type not is a string