日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

時間戳轉日期格式-自動補零,日期格式轉時間戳

作者:狐逍超 更新時間: 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

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新