学无先后,达者为师

网站首页 编程语言 正文

时间戳转日期格式-自动补零,日期格式转时间戳

作者:狐逍超 更新时间: 2023-10-09 编程语言

一、时间戳转换为日期格式,直接拷贝使用即可-自动补零

    //将时间戳转换成日期格式
    timestampToTime(timestamp) {
      let date = new Date(timestamp * 1000); //时间戳为10位需*1000
      let Y = date.getFullYear() + "-"; //年
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-"; // 月
      let D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " "; //日
      let h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":"; //时
      let m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":"; //分
      let s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); //秒
      return Y + M + D + h + m + s;
    },

结果 

let data = this.timestampToTime(1680836109);

console.log(data);  // 2023-04-07 10:55:09;

如果需要自定义日期格式的话可以加一个传参

timestamp: 时间戳   ;type:需要的日期符号

    timestampToTime(timestamp, type) {
      let date = new Date(timestamp * 1000); //时间戳为10位需*1000
      let Y = date.getFullYear(); //年
      let M =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1; // 月
      let D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " "; //日
      let h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":"; //时
      let m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":"; //分
      let s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); //秒
      return Y + type + M + type + D + h + m + s;
    },

结果 

let data = this.timestampToTime(1680836109, "/");

console.log(data); //2023/04/07 10:55:09;

二、日期转时间戳

let num = Date.parse("2023-04-07 10:55:09");  // 日期格式不用管-直接丢进去就行

let list = String(Date.parse("2023/04/07 10:55:09")).slice(0, 10);

console.log(num / 1000); //1680836109

console.log(list); //1680836109

注:日期格式无所谓-直接放进去就行
总结:直接复制即可 

原文链接:https://blog.csdn.net/m0_57884221/article/details/130007590

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新