JavaScript 时间类型转化为字符类型
const yyyy = 'yyyy', MM = 'MM', dd = 'dd', HH = 'HH', mm = 'mm', ss = 'ss'
/**
* date:时间类型,若非时间类型,直接返回date
* format:时间格式,默认为:yyyy-MM-dd HH:mm:ss
*/
function format(date, format) {
if (!(date instanceof Date)) {
return date
}
var dateStr = '';
if (null == format || '' == format) {
format = 'yyyy-MM-dd HH:mm:ss'
}
if (format.indexOf(yyyy) > -1) {
var y_M = ''
var y_M_index = null
if (format.indexOf('yM') == -1) {
y_M = format.slice(yyyy.length, format.indexOf('M'))
y_M_index = format.indexOf(y_M) + 1
} else {
y_M_index = format.indexOf('M')
}
dateStr = date.getFullYear() + y_M
format = format.slice(y_M_index)
}
if (format.indexOf(MM) > -1) {
var M_d = ''
var M_d_index = null
if (format.indexOf('Md') == -1) {
M_d = format.slice(MM.length, format.indexOf('d'))
M_d_index = format.indexOf(M_d) + 1
} else {
M_d_index = format.indexOf('d')
}
var month = date.getMonth() + 1
month = month < 10 ? '0' + month : month
dateStr = dateStr + month + M_d
format = format.slice(M_d_index)
}
if (format.indexOf(dd) > -1) {
var d_H = ''
var d_H_index = null
if (format.indexOf('dH') == -1) {
d_H = format.slice(dd.length, format.indexOf('H'))
d_H_index = format.indexOf(d_H) + 1
} else {
d_H_index = format.indexOf('H')
}
var day = date.getDate()
day = day < 10 ? '0' + day : day
dateStr = dateStr + day + d_H
format = format.slice(d_H_index)
}
if (format.indexOf(HH) > -1) {
var H_m = ''
var H_m_index = null
if (format.indexOf('Hm') == -1) {
H_m = format.slice(HH.length, format.indexOf('m'))
H_m_index = format.indexOf(H_m) + 1
} else {
H_m_index = format.indexOf('m')
}
var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
dateStr = dateStr + hour + H_m
format = format.slice(H_m_index)
}
if (format.indexOf(mm) > -1) {
var m_s = ''
var m_s_index = null
if (format.indexOf('ms') == -1) {
m_s = format.slice(mm.length, format.indexOf('s'))
m_s_index = format.indexOf(m_s)
} else {
m_s_index = format.indexOf('s')
}
var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
dateStr = dateStr + minutes
if (format.indexOf(ss) > -1) {
dateStr = dateStr + H_m
}
format = format.slice(m_s_index)
}
if (format.indexOf(ss) > -1) {
var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
dateStr = dateStr + seconds
}
return dateStr
}
网友可以把上述代码写成循环的形式,提高代码复用性。
写得不好,仅供参考。