小程序-将年月日时分秒转为刚刚,几小时前,几天前,几周前,几月前(小程序不兼容Date.parse(),需要将时间中的“-”转为“/”)

=========app.js

checkData:function(stringTime){
  console.log("stringTime:",stringTime)
  var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var week = day * 7;
    var month = day * 30;
    var time1 = new Date().getTime();//当前的时间戳
    console.log("time1:",time1);
    console.log("stringTime:",stringTime)
    var time2 = Date.parse(stringTime.replace(/-/g, '/'));//指定时间的时间戳
    console.log("time2:",time2);
    var time = time1 - time2;
    console.log("time:",time);
    var result = null;
    if (time < 0) {
        alert("设置的时间不能早于当前时间!");
    } else if (time / month >= 1) {
        result = parseInt(time / month) + "月前";
    } else if (time / week >= 1) {
        result = parseInt(time / week) + "周前";
    } else if (time / day >= 1) {
        result = parseInt(time / day) + "天前";
    } else if (time / hour >= 1) {
        result = parseInt(time / hour) + "小时前";
    } else if (time / minute >= 1) {
        result = parseInt(time / minute) + "分钟前";
    } else {
        result = "刚刚发布!";
    }
    return result;
    
},

  

使用页面js调用方法:app.checkData(‘2022-06-30 11:34:30’)

 

强调:小程序不兼容Date.parse(),需要将时间中的“-”转为“/”;

Date.parse()通过标准时间格式转换成时间戳,

开发者工具上正常,但是到iphone真机上报错,

原因是iPhone上不支持 2022-06-30 11:34:30 格式,

需转换成 2022/06/30 11:34:30

date = "2022-06-30 11:34:30"

用正则将'-'替换成'/'

let time2 = Date.parse(date.replace(/-/g, '/'))

posted @ 2022-06-30 11:40  MiniDuck  阅读(164)  评论(0编辑  收藏  举报