直接通过new Date出来的时间不符合我们的习惯,
node.js中的dateformar插件可以对时间进行处理,使用 方式如下
1 下载dateformat插件 npm install dateformat
2 在js中引入dateformat模块
3 导入模块变量
const template=require('art-template');
const path=require('path');
const dateformat=require('dateformat');
const views=path.join(__dirname,'view','06.art');
//导入模板变量,使处理函数是template里的一个方法
template.defaults.imports.dateformat=dateformat;
const html=template(views,{
time:new Date(),
})
console.log(html);
4 在模板.art中使用
{{dateformat(time,'yyyy-mm-dd HH:MM:ss')}}
结果是 2019-10-07 13:40:53
自己封装的处理时间函数
function dateFormat(date, format) {
if (typeof date === 'string') {
var mts = date.match(/(\/Date\((\d+)\)\/)/)
if (mts && mts.length >= 3) {
date = parseInt(mts[2])
}
}
date = new Date(date)
if (!date || date.toUTCString() === 'Invalid Date') {
return ''
}
var map = {
'M': date.getMonth() + 1, // 月份
'd': date.getDate(), // 日
'h': date.getHours(), // 小时
'm': date.getMinutes(), // 分
's': date.getSeconds(), // 秒
'q': Math.floor((date.getMonth() + 3) / 3), // 季度
'S': date.getMilliseconds() // 毫秒
}
format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
var v = map[t]
if (v !== undefined) {
if (all.length > 1) {
v = '0' + v
v = v.substr(v.length - 2)
}
return v
} else if (t === 'y') {
return (date.getFullYear() + '').substr(4 - all.length)
}
return all
})
return format
}
在需要的地方调用方法
dateFormat(时间,'时间格式') 转换的时间格式如下
let time = 'Tue Feb 26 2019 00:00:00 GMT+0800' 或者
time = '2020-04-23 23:32:03'
dateFormat(time,'yyyy-MM-dd hh:mm:ss')
dateFormat(time,'yyyy-MM-dd')