獲取當前時間的標准時間,轉換為年月日,時分秒的格式;以及dayjs的應用 獲取年月日時分秒的時間格式 計算時間差 使用dayjs如何計算時間差 獲取當前年月日 取絕對值 版權 一句代碼獲取年月日格式的時間 let YMD= new Date().toLocaleDateString() console.log(YMD) // 2019/10/12 new Date()后轉換的當前時間:結果如: 2019-10-12 15:19:33 // new Date() 獲取當前標准時間,轉為:YYYY-MM-DD h:m:s (年月日 時分秒) 格式 getCurrentTime () { let date = new Date() 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 hours = date.getHours() let minutes = date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes() let seconds = date.getSeconds() < 10 ? ('0' + date.getSeconds()) : date.getSeconds() date = Y + '-' + M + '-' + D + ' ' + hours + ':' + minutes + ':' + seconds console.log(date) //2019-10-12 15:19:33 return date } // **新寫法:** 給 slice() 傳入負值索引 ( 2021.3.25更新 博客內容 ) getCurrentTime() { let date = new Date(); let Y = date.getFullYear(); let M = this.getStr(date.getMonth() + 1); let D = this.getStr(date.getDate()); let hours = date.getHours(); let minutes = this.getStr(date.getMinutes()); let seconds = this.getStr(date.getSeconds()); date =Y + "-" + M + "-" + D + " " + hours + ":" + minutes + ":" + seconds; console.log(date); //2019-10-12 15:19:33 return date; }, getStr(point) { return ("00" + point).slice(-2); // 從字符串的倒數第二個字符開始截取,一直截取到最后一個字符;(在這里永遠截取該字符串的最后兩個字符) }, 用dayjs 轉換的當前時間:結果如:2019-10-12 15:19:33 安裝**dayjs** : npm install dayjs --save 或者 yarn add dayjs 1 引入**dayjs**: 1). 在單文件中直接用import引入它: import dayjs from 'dayjs' 或者 2). 新建一個js文件(文件名可以隨意取),如:dayjs.js,在該js文件中引入dayjs,並導出 var dayjs = require(‘dayjs’); export default dayjs; 在需要用到dayjs的文件中引入你創建的dayjs.js文件。import dayjs from '@/plugins/dayjs.js'(這里我創建的dayjs.js文件是放在vue項目下src目錄下的plugins的) 在文件中使用dayjs: // 用dayjs將獲取的當前時間轉為年月日時分秒的格式 getDayjsTime () { let dayjsTime = dayjs(`${new Date()}`).format('YYYY-MM-DD HH:mm:ss') console.log(currTime) // 2019-10-12 15:19:33 return dayjsTime } dayjs計算兩個時間相差的天數 dayjs獲取的時間對象的diff方法, Math.abs() 表示 對時間差取絕對值 // 獲取時間差,相差的天數 getDiffTime () { const date1 = dayjs('2019-9-12') const date2 = dayjs('2019-10-12') let diffTime = Math.abs(date1.diff(date2, 'day'))//獲取兩個時間對象相差的天數,取絕對值。 console.log(diffTime) // 30 return diffTime } 關於dayjs,具體可參考 https://github.com/iamkun/dayjs以及一些相關的技術博客。 ———————————————— 版權聲明:本文為CSDN博主「ddx2019」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。 原文鏈接:https://blog.csdn.net/ddx2019/article/details/102535557