微信小程序在怎么利用wxs对日期时间进行处理,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
1、时间戳转日期
在wxs中处理日期需要使用getDate(time),而不能使用new Date()来处理日期
在wxs文件中
var filter = { formatNumber: function (n) { n = n.toString() return n[1] ? n : '0' + n }, parseTime: function (time, type) { if (time == null || type == '') { return '' } if (arguments.length === 0) { return null } var date = getDate(time);//在wxs中不能使用new Date()来处理日期 console.log("date", date); var y = date.getFullYear(); var m = filter.formatNumber(date.getMonth() + 1); var d = filter.formatNumber(date.getDate()); var h = filter.formatNumber(date.getHours()); var i = filter.formatNumber(date.getMinutes()); var s = filter.formatNumber(date.getSeconds()); var a = filter.formatNumber(date.getDay()); var time_str = ""; if (type == 'month') { time_str = y + '-' + m; } else if (type == 'date') { time_str = y + '-' + m + '-' + d; } else if (type == 'datetime') { time_str = y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s; } else if (type == 'onlyMonth') { time_str = m; } else if (type == 'onlyYear') { time_str = y; } return time_str }, }module.exports = { parseTime: filter.parseTime,}
在wxml中使用
<wxs module="filters" src="../../../filters/filter.wxs"></wxs><text>{{filters.parseTime(time,'date')}}</text>
2、UTC转北京时间
UTC时间比北京时间晚8小时,在苹果手机上需要去除"Z"后再处理时间
var filter = { formatNumber: function (n) { n = n.toString() return n[1] ? n : '0' + n }, parseTime: function (time, type) { if (time == null || time == '') { return '' } if (arguments.length === 0) { return null } var date; if (typeof time === 'object') { date = time } else { if (('' + time).length === 10) { time = parseInt(time) * 1000 } else { time = time.replace("Z", " ").replace(getRegExp('-', 'g'), "/")//去除Z,兼容苹果手机 var ts = time.split('T') var t1 = ts[0] var t2 = ts[1].split('.')[0] time = t1 + " " + t2 time = getDate(time).getTime() + 8 * 3600000;//utc时间与北京时间相差8小时 } date = getDate(time)//不能使用new Date() } var y = date.getFullYear(); var m = filter.formatNumber(date.getMonth() + 1); var d = filter.formatNumber(date.getDate()); var h = filter.formatNumber(date.getHours()); var i = filter.formatNumber(date.getMinutes()); var s = filter.formatNumber(date.getSeconds()); var a = filter.formatNumber(date.getDay()); var time_str = ""; if (type == 'month') { time_str = y + '-' + m; } else if (type == 'date') { time_str = y + '-' + m + '-' + d; } else if (type == 'datetime') { time_str = y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s; } else if (type == 'onlyMonth') { time_str = m; } else if (type == 'onlyYear') { time_str = y; } return time_str },}module.exports = { parseTime: filter.parseTime,}
看完上述内容,你们掌握微信小程序在怎么利用wxs对日期时间进行处理的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注编程网行业资讯频道,感谢各位的阅读!