將 Date 類型數據轉換成標准的 時間格式 YY-MM-DD HH:mm:SS


  在 前端 獲得 Date 類型數據的途徑主要由兩種方式:

  • 在前端界面通過一些組件或者標簽獲取用戶選擇的 時間;
  • 在 js 通過 new Date 的方式,創建獲取當前時間的變量;
  • 在調用接口是,后端返回的數據中,字段的值為 Date(******+***) 的字符串;

一、通過前端界面獲取的 時間:

  此處通過 element -UI 中的日期時間選擇器 組件進行測試;

  1、新建一個 vue 文件,把日期時間選擇器 組件放入到代碼中:

<template>
  <div>
    <div class="block">
      <span class="demonstration">默認</span>
      <el-date-picker
        v-model="datas"
        type="datetime"
        placeholder="選擇日期時間">
      </el-date-picker>
      <el-button @click="printTime()">打印</el-button>
    </div>
  </div>
</template>

  2、在data() 方法中,初始化一個與組件中雙向綁定的變量 datas:

data() {
    return {
      datas: '',
    };
  },

  3、添加一個按鈕,用於在控制台打印出 變量datas的值:

<template>
  <div>
    <div class="block">
      <span class="demonstration">默認</span>
      <el-date-picker
        v-model="datas"
        type="datetime"
        placeholder="選擇日期時間">
      </el-date-picker>
      <el-button @click="printTime()">打印</el-button>
    </div>
  </div>
</template>

  同時在 methods 中添加打印按鈕點擊的事件:

methods: {
    printTime() {
      console.info(this.datas);
      console.info(typeof(this.datas));
      console.info(this.datas.getFullYear());
      console.info(this.datas.getMonth() + 1);
      console.info(this.datas.getDate());
      console.info(this.datas.getHours());
      console.info(this.datas.getMinutes());
      console.info(this.datas.getSeconds());
    },
  }

  測試結果為:

二、 通過在 js 新建 Date 類型的方式:

  

    // 新建一個 Date 對象類型的變量
    let date = new Date();
    console.info(date);
    function formatDate(date) {
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let hour = date.getHours();
        let minute = date.getMinutes();
        let second = date.getSeconds();
        console.info(year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
    }
    formatDate(date);

  結果為:

三、通過在 后端返回數據 的方式

  此處通過 聲明 Date(******+***) 的變量方式來模擬后端返回帶有此類值的情況:

  *此處不考慮\有多少,只是在字符串中的轉義方式;

    // 模擬后端傳遞 '\\/Date(******+***)\\/' 字符串的Date類型數據
    let data = '\\\\/Date(1633277719000+0800)\\\\/'
    // 聲明處理該類型數據的統一方法
    function formatStringDate(date) {
        let tmp = /\d+(?=\+)/.exec(date.substr(1, date.length - 1));
        let data = new Date(+tmp);
        let year = data.getFullYear();
        let month = data.getMonth() + 1;
        let day = data.getDate();
        let hour = data.getHours();
        let minute = data.getMinutes();
        let second = data.getSeconds();
        console.info(year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
    }
    // 調用該方法進行轉換
    formatStringDate(data);

  結果為:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM