微信小程序通用时间格式 WXS
废话不多说直接上代码 time.wxs 文件代码如下
var formatDate = function (datetime, type) {
var str = type ? type : "yyyy-MM-dd hh:mm:ss" //默认格式
var date = getDate(datetime);
var year = date.getFullYear(); //年
var month = date.getMonth() + 1 > 10 ? date.getMonth() + 1 : ('0' + (date.getMonth() + 1)); //月
var day = date.getDate() > 10 ? date.getDate() : '0' + date.getDate(); //日
var hours = date.getHours() > 10 ? date.getHours() : '0' + date.getHours() //时
var minutes = date.getMinutes() > 10 ? date.getMinutes() : '0' + date.getHours() //分
var seconds = date.getSeconds() > 10 ? date.getSeconds() : '0' + date.getSeconds() //秒
// console.log(year,month,day,hours,minutes,seconds)
str = str.replace(getRegExp('yyyy', 'g'), year)
str = str.replace(getRegExp('MM', 'g'),month)
str = str.replace(getRegExp('dd', 'g'),day)
str = str.replace(getRegExp('hh', 'g'),hours)
str = str.replace(getRegExp('mm', 'g'),minutes)
str = str.replace(getRegExp('ss', 'g'),seconds)
// console.log(str, 484848)
// return [year, month, day].map(formatNumber).join('-');
return str
}
module.exports = {
formatDate: formatDate
}
使用方式
/*引入time.wxs文件*/
<wxs src="../../wxs/time.wxs" module="time" />
/* createTime 为需要格式化的时间 */
{{time.formatDate(createTime)}}
/* 别的时间格式 例: **年**月**日 **:**:** */
{{time.formatDate(createTime,'yyyy年MM月dd日 hh:mm:ss')
这样就能像过滤器一样格式化时间了,代码中有什么不足的地方请在评论告诉我,加以改正。