微信小程序 /Date(1537326774000) 字符串(时间戳)转日期

微信小程序 /Date(1537326774000) 字符串(时间戳)转日期

看了网上的博客,现在是真不靠谱,全是复制粘贴别人的,还不对,真是恶心人,自己写了下,分享给大家 ,省点时间,多敲点代码。

微信小程序 /Date(1537326774000) 字符串(时间戳)转日期

首先,把util.js里的内容替换成下列代码。

 

年月日时分
// util.js
//时间戳转换成日期时间


function date_time(val) {


  var date = new Date(parseInt(val.replace("/Date(", "").replace(")/", ""), 10));


  //月份为0-11,所以+1,月份小于10时补个0
  var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;


  var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();


  var hour = date.getHours();


  var minute = date.getMinutes();


  var second = date.getSeconds();


  var theTime = date.getFullYear() + "-" + month + "-" + currentDate + " " + hour + ":" + minute + ":" + second;

  return theTime ;


}
module.exports = {


  date_time: date_time


}

其次,在需要转换时间戳的地方 引用 util.js

var util = require("../../utils/util.js");

 

wx.request({

    url: 'url',

header: {

    'content-type': 'application/json'

},

success:function(res) {

    var datas = res.data.data;

    for (var i in datas) {

        datas[i].CreateTime = util.date_time(datas[i].CreateTime)

         //这里是主要代码,获取数据中的【CreateTime: /Date(1537326774000)/】

    }

    that.setData({

        news: datas,

    })

    console.log(res.data.data)//通过打印可以看到 已经将/Date(1537326774000)/ 转换成2018-09-19 11:12:54

 

微信小程序 /Date(1537326774000) 字符串(时间戳)转日期

    }

})