原生写法
定义格式化时间方法
*
* @param {*} dtStr 需要格式化的时间
* @param {*} symbol 返回的时间对象格式
* 默认 symbol: {before: '-', after: ':'} yyyy-mm-dd hh:mm:ss
*/
function dateFormat(dtStr, symbol = { before: '-', after: ':' }) {
const dt = new Date(dtStr)
const y = dt.getFullYear() // 年
const m = zeroFilling(dt.getMonth() + 1) // 月
const d = zeroFilling(dt.getDate()) // 日
const h = zeroFilling(dt.getHours()) // 时
const min = zeroFilling(dt.getMinutes()) // 分
const s = dt.getSeconds() // 秒
return (
y + symbol.before + m + symbol.before + d
+ ' ' +
h + symbol.after + min + symbol.after + s
)
}
// 补零函数
function zeroFilling(num) {
return num >= 10 ? num : (0 + '' + num)
}
// 导出函数
module.exports = {
dateFormat
}
npm包写法
const moment = require('moment')
const dt = moment().format('YYYY-MM-DD HH:mm:ss')
console.log(dt)