目录

微信小程序-js-时间戳与日期格式的转换

微信小程序-js-时间戳与日期格式的转换

一、 成日期格式

1、代码片段
function timestampToTime(value, type = 0){
    var time = new Date(value);
    var year = time.getFullYear();
    var month = time.getMonth() + 1;
    var date = time.getDate();
    var hour = time.getHours();
    var minute = time.getMinutes();
    var second = time.getSeconds();
    month = month < 10 ? "0" + month : month; 
    date = date < 10 ? "0" + date : date; 
    hour = hour < 10 ? "0" + hour : hour; 
    minute = minute < 10 ? "0" + minute : minute; 
    second = second < 10 ? "0" + second : second; 
    var arr = [ 
        year + "-" + month + "-" + date, 
        year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second, 
        year + "年" + month + "月" + date, 
        year + "年" + month + "月" + date + " " + hour + ":" + minute + ":" + second, 
        hour + ":" + minute + ":" + second 
    ] 
    return arr[type]; 
} 

使用方法:

timestampToTime(1591841249)   //返回2020-06-11

timestampToTime(1591841249,1) //返回 2020-06-11 10:10:10

timestampToTime(1591841249,2)   //返回2020年06月11日

2、微信小程序中,时间戳转换成日期格式的具体步骤
(1)在utils文件夹下创建一个 js文件,在此js文件中 export 上面的代码片段

https://i-blog.csdnimg.cn/blog_migrate/26704e665c4a6d04245fdfa3e904e198.png

(2)在需要引入的页面的 js文件中引入,需要注意的是对应的方法名称和此应的文件路径
 import {timestampToTime} from "../../utils/common.js"

https://i-blog.csdnimg.cn/blog_migrate/47a3ea24deac1dced8309a0ef8f70413.png

(3)在需要引入的页面的 js文件中使用此方法
success:(res)=>{
      console.log(res);
      //遍历每一个对象
      res.data.data.forEach(item=>{
       item.publish_date=timestampToTime(item.publish_date)
      })
      this.setData({
        newsARR:res.data.data
      })
    }

https://i-blog.csdnimg.cn/blog_migrate/0046be7e077ca99d3bb7b0486c8fe2b5.png

二、 成时间戳

var date = new Date("2022-12-04 17:15:53:555");
// 有三种方式获取
var time1 = date.getTime();
var time2 = date.valueOf();
var time3 = Date.parse(date);
console.log(time1); //1670145353555
console.log(time2); //1670145353555
console.log(time3); //1670145353000