小程序把日期格式转成几周前、几月前、几年前、几天前

小程序wxml页面

<view>
<view wx:for="{{newsList}}" wx:key="index" class="text-center">
<view class="cu-tag round ">{{item.time}}</view>
</view>
</view>

小程序js页面

const util = require('../../utils/util')


 data: {
    newsList: [{
      time: "2021-06-25",

    }]
  },

 getList() {
    var that = this;
    let newsList = that.data.newsList;
    let newList = [];
    newsList.forEach(element => { // 使用forEach循环获得的数组
      let result = util.getDateDiff(element.time) //将获取的年月日通过 getDateDiff 函数转换成几小时前,几天前等等,然后将其赋值到对象 result 上
      element.time = result // 将数组中的年月日替换成 result 
      newList.push(element) // 然后在吧所有修改过日期的数据添加到 newList 数组中
    });
    console.log(newList)
    that.setData({
      newsList: newList // 将newList返回给list
    })
  },

util.js页面

function getDateDiff(dateTime) {   // 将年月日转换为几小时前,几天前等等
  let dateTimeStamp = new Date(dateTime).getTime();
  let result = '';
  let minute = 1000 * 60;
  let hour = minute * 60;
  let day = hour * 24;
  let halfamonth = day * 15;
  let month = day * 30;
  let year = day * 365;
  let now = new Date().getTime();
  let diffValue = now - dateTimeStamp;
  if (diffValue < 0) {
    return;
  }
  let monthEnd = diffValue / month;
  let weekEnd = diffValue / (7 * day);
  let dayEnd = diffValue / day;
  let hourEnd = diffValue / hour;
  let minEnd = diffValue / minute;
  let yearEnd = diffValue / year;
  if (yearEnd >= 1) {
    result = dateTime;
  } else if (monthEnd >= 1) {
    result = "" + parseInt(monthEnd) + "月前";
  } else if (weekEnd >= 1) {
    result = "" + parseInt(weekEnd) + "周前";
  } else if (dayEnd >= 1) {
    result = "" + parseInt(dayEnd) + "天前";
  } else if (hourEnd >= 1) {
    result = "" + parseInt(hourEnd) + "小时前";
  } else if (minEnd >= 1) {
    result = "" + parseInt(minEnd) + "分钟前";
  } else {
    result = "刚刚";
  }
  return result;
};
//暴露的跟引用页面的一样可简写成一个
module.exports = {
 getDateDiff
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值