VUE 獲取今天時間和一月前今天的時間
這個場景是啥呢,就比如說一個圖表,需要默認查取過去一個月的數據,所以說需要向后台傳輸兩個參數,一個是開始時間,一個是結束時間。獲取當前時間還好,一個月前的時間有點費勁,當然方法很多,下面是其中一種,可以轉換成一個星期或者是半個月都可以。
首先先創建一個變量用來存儲開始時間和結束時間。
timeParams: {
beginDate : '', // 開始時間 例如:2020-09-16 14:25:23
endDate: '' // 結束時間 例如:2020-10-16 14:25:23
},
定義一個方法來初始化時間。
this.initTime(); // 初始化時間
這個方法這樣寫。
// 初始化時間
initTime() {
const endDate = this.getFormatDate(new Date()).substr(0, 11) + '23:59:59'
const beginDate = this.getFormatDate(new Date(new Date() - 3600 * 1000 * 24 * 29)).substr(0, 11) + '00:00:00'
this.timeParams = {
'startTime': beginDate,
'endTime': endDate
}
},
處理時間
// 獲取當前時間
getFormatDate(date) {
var month = date.getMonth() + 1
var strDate = date.getDate()
if (month >= 1 && month <= 9) {
month = '0' + month
}
if (strDate >= 0 && strDate <= 9) {
strDate = '0' + strDate
}
var currentDate = date.getFullYear() + '-' + month + '-' + strDate + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
return currentDate
},