微信小程序调用时间的三种方法

1.更改后端时间戳

//wxml


{{Formater.formatDatetime(publisherTime,"yyyy/MM/dd hh:mm")}}

//ts
data:{
   publisherTime: 1660714987000,
  }
//日期格式化----Datatime代码段---------------------------------------------------------
var formatDatetime = function (timestamp, format = "yyyy-MM-dd hh:mm:ss") {

    if (!timestamp) {
        return "null"
    }

    var realDate = getDate(timestamp);
    var regYear = getRegExp("(y+)", "i");
    var date = [
        ["M+", realDate.getMonth() + 1],
        ["d+", realDate.getDate()],
        ["h+", realDate.getHours()],
        ["m+", realDate.getMinutes()],
        ["s+", realDate.getSeconds()],
        ["q+", Math.floor((realDate.getMonth() + 3) / 3)],
        ["S+", realDate.getMilliseconds()],
    ];
    var reg1 = regYear.exec(format);
    if (reg1) {
        format = format.replace(reg1[1], (realDate.getFullYear() + '').substring(4 - reg1[1].length));
    }
    for (var i = 0; i < date.length; i++) {
        var reg2 = getRegExp("(" + date[i][0] + ")").exec(format);
        if (reg2) {
            format = format.replace(reg2[1], reg2[1].length == 1 ? v : ("00" + date[i][1]).substring(("" + date[i][1]).length));
        }
    }
    return format;
};




var timeUnitFormat = function (unit) {
    var map = {
        "HOURS": "时",
        "DAY": "天",
        "MONTH": "月",
        "YEAR": "年"
    }
    return map[unit] ? map[unit] : "null";
}



var inclued = function (array, item) {
    return array.indexOf(item) > -1
}




var formatNum = function (n, m = 0) {
    return n.toFixed(m)
}



module.exports = {
    formatDatetime: formatDatetime, //日期格式化
    timeUnitFormat: timeUnitFormat,
    publisherTypeFormat: publisherTypeFormat,
    formatNum: formatNum,
    inclued: inclued
}

2.更改后端时间戳

formatTimeTwo(number, format) {
    var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
    var returnArr = [];
    var date = new Date(number * 1000);
    returnArr.push(date.getFullYear());
    returnArr.push((date.getMonth() + 1));
    returnArr.push((date.getDate()));
    returnArr.push((date.getHours()));
    returnArr.push((date.getMinutes()));
    returnArr.push((date.getSeconds()));

    for (var i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
  },

3.获取本地时间

let dataTime
  let yy = new Date().getFullYear()
  let mm = new Date().getMonth()+1
  let dd = new Date().getDate()
  let hh = new Date().getHours()
  let mf = new Date().getMinutes()<10?'0'+new Date().getMinutes():
    new Date().getMinutes()
  let ss = new Date().getSeconds()<10?'0'+new Date().getSeconds():
    new Date().getSeconds()
    dataTime = `${yy}.${mm}.${dd} ${hh}:${mf}:${ss}`;
    this.setData({
      dataTime:dataTime
    })

你可能感兴趣的:(微信小程序,微信小程序,小程序)