微信小程序wxml页面实现对时间戳格式转换

本文介绍了如何在微信小程序的WXML页面中处理从数据库获取的时间戳,通过创建WXS文件实现时间差显示和时间格式化。通过示例代码展示了getGapTime和dateFormat两个函数的用法,用于将时间戳转换为易于阅读的格式,如‘刚刚’、‘分钟前’等,并解决因未乘以1000导致的1970年错误。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

从数据库中返回的文章发布时间为时间戳,想在wxml页面调用的时候直接进行转换
尝试了下使用wxs,最后实现了需要的效果
部分代码为网上参考,此处记录下
首先新建一个my.wxs文件
其中写了两个函数 一个将时间戳处理为时间,另一个判断时间与当前时间的差值
function getGapTime(date) {
var re = “00”

var timestamp = getDate().getTime();
timestamp = parseInt(timestamp / 1000);
//发表文章的时间戳 s
var publicstamp = getDate(date).getTime();
publicstamp = parseInt(publicstamp / 1000)
//时间差s
var gap = timestamp - publicstamp

if (gap < 60) {
re = “刚刚”
} else if (gap < 60 * 60) {
re = parseInt(gap / 60) + “分钟前”
} else if (gap < 60 * 60 * 24) {
re = parseInt(gap / 60 / 60) + “小时前”
} else if (gap < 60 * 60 * 24 * 30) {
re = parseInt(gap / 60 / 60 / 24) + “天前”
} else {

re = date.substring(0, 10)  //时间超过1个月返回具体的 年-月-日

}
return re
}
var formatNumber = function (n) {
n = n.toString()
return n[1] ? n : ‘0’ + n
}

var regYear = getRegExp("(y+)", “i”);

var dateFormat = function (timestamp, format) {
if (!format) {
format = “yyyy-MM-dd hh:mm:ss”;
}
timestamp = parseInt(timestamp);
var realDate = getDate(timestamp);
function timeFormat(num) {
return num < 10 ? ‘0’ + num : num;
}
var date = [
[“M+”, timeFormat(realDate.getMonth() + 1)],
[“d+”, timeFormat(realDate.getDate())],
[“h+”, timeFormat(realDate.getHours())],
[“m+”, timeFormat(realDate.getMinutes())],
[“s+”, timeFormat(realDate.getSeconds())],
[“q+”, Math.floor((realDate.getMonth() + 3) / 3)],
[“S+”, realDate.getMilliseconds()],
];
var reg1 = regYear.exec(format);
// console.log(reg1[0]);
if (reg1) {

format = format.replace(reg1[1], (realDate.getFullYear() + '').substring(4 - reg1[1].length));

}
for (var i = 0; i < date.length; i++) {
var k = date[i][0];
var v = date[i][1];

var reg2 = getRegExp("(" + k + ")").exec(format);
if (reg2) {
  format = format.replace(reg2[1], reg2[1].length == 1
    ? v : ("00" + v).substring(("" + v).length));
}

}
return format;
}
module.exports = {
getGap: getGapTime,
dateFormat: dateFormat
}
在wxml页面中进行调用

{{my.getGap(aaa.dateFormat(item.pubdate*1000))}}
此处乘以1000是因为后台数据来源于dedecms,刚开始取数据一直显示1970年,发现是因为没有乘以1000,最终实现如下效果
在这里插入图片描述

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值