页面动态处理时间,wxs文件处理服务器时间报错,显示不正常,如何处理?
发布于 6 年前 作者 na79 831 次浏览 来自 问答

大家好:

我是小程序云开发是遇到这个问题,数据保存到云数据库的代码如下:
const db = wx.cloud.database();
        var time = new Date();
        db.collection('asarlar').add({
            // data 字段表示需新增的 JSON 数据
            data: {
              asarName: this.data.asarName,
              asarNamehan: this.data.asarNamehan,
              asarAuthor: this.data.asarAuthor,
              asarType: this.data.asarType,
              asarType1: this.data.asarType1,
              asarPrice: this.data.asarPrice,
              asarContant: this.data.asarContant,
              asarContanthan: this.data.asarContanthan,
              asarPic: this.data.imagesfileID,
              asarDate: time,
              //asarDate: db.serverDate(),
              asarcount: 0
            }          })
var time = new Date(); 和db.serverDate() 这两种时间获取都试了,保存数据库的时间正常,没问题。

然后首页加载数据时,从数据库读取时间,通过循环显示多个信息(都包含时间),我想只显示年月日,所以通过wxs时间处理来动态处理时间并显示,代码如下:(这个时间处理网上找了很多)

  formatTime: function (timestamp) {
    var date = getDate(timestamp);
    var year = date.getFullYear();
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    var over_time = year + "/" + month + "/" + day + " " + hours + ":" + minutes + ":" + seconds
    //***至此以上是将时间2020-03-18T01:57:23.000+0000转为正常时间格式,以下为将时间进行增加8小时解决时区差异的操作***
    var time = getDate(Date.parse(over_time));
    time.setTime(time.setHours(time.getHours() + 8));

    //默认时分秒年月日
    return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ":" + seconds;
  },
t通过console.log 显示读取的数据时发现时间是这样的:

转换成后显示页面的时候时间显示成nan-nan-nan 这样,我看转换错误,是什么问题请指点指点,谢谢。

3 回复

题e-dlkrccdflbbflr#vmrhvvlmfzin.f# . vrdd@ffffddcffd-rftttd4510409

改成:var time = Date.now()

/**
 * 当前 日期
 * 输出格式:
 * 2018-01-02 04:05:06
 */
function NowDate() {
  const date = new Date();
  const y = date.getFullYear(); //年
  const m = date.getMonth() + 1//月
  const d = date.getDate(); //日
  const h = date.getHours(); //时
  const mm = date.getMinutes(); //分
  const s = date.getSeconds(); //秒
  return y + "-" + check(m) + "-" + check(d) + " " + check(h) + ":" + check(mm) + ":" + check(s);
}

// 补足2位数
function check(e{
  return e.toString().length < 2 ? '0' + e : e
}
回到顶部