一、獲取日期
// 獲取日期方法(date為當天日期,i為相隔天數,例如:獲取明天日期,則將i=1傳入)
getDate (date, i) {
if (date === undefined || date === null) {
date = new Date();
}
let month, day;
date.setTime(date.getTime() + i * 24 * 60 * 60 * 1000);
month = date.getMonth() + 1 < 10 ? '0' + parseInt(date.getMonth() + 1) : date.getMonth() + 1;
day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
let time = date.getFullYear() + "-" + month + "-" + day;
return time;
}
二、獲取本月第一天和最后一天
/**
* 獲取本月第一天和最后一天
*/
getMonthStartAndEndDate () {
let nowDate = new Date()
let nowYear = nowDate.getFullYear() // 當前年
let nowMonth = nowDate.getMonth() // 當前月(值為0~11)
let firstDate = new Date(nowYear, nowMonth, 1)
let lastDate = new Date(nowYear, (nowMonth + 1), 0)
let list = []
list[0] = this.initDateFormat(firstDate)
list[1] = this.initDateFormat(lastDate)
return list
},
/**
* 格式化時間數據
*/
initDateFormat (date) {
let month = date.getMonth() + 1 < 10 ? '0' + parseInt(date.getMonth() + 1) : date.getMonth() + 1
let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
return date.getFullYear() + '-' + month + '-' + day
},
三、獲取指定月份的第一天和最后一天
/**
* 獲取指定月份(格式:yyyy-MM)第一天和最后一天,例如:2022-06,2022-06-01 2022-06-30
*/
function getRequireMonthStartAndEndDate (month) {
let index = month.lastIndexOf('-')
let nowYear = parseInt(month.substr(0, index)) // 當前年
let nowMonth = parseInt(month.substr(index + 1)) - 1 // 當前月(值為0~11)
let firstDate = new Date(nowYear, nowMonth, 1)
let lastDate = new Date(nowYear, (nowMonth + 1), 0)
let list = []
list[0] = initDateFormat(firstDate)
list[1] = initDateFormat(lastDate)
console.log(nowYear, nowMonth, firstDate, lastDate, list[0], list[1])
return list
}
四、獲取本年第一天到本月最后一天
/**
* 獲取本年第一天和到本月最后一天
*/
function getYearStartAndMonthEndDate () {
let nowDate = new Date()
let nowYear = nowDate.getFullYear() // 當前年
let nowMonth = nowDate.getMonth() // 當前月(值為0~11)
let firstDate = new Date(nowYear, 0, 1)
let lastDate = new Date(nowYear, (nowMonth + 1), 0)
let list = []
list[0] = initDateFormat(firstDate)
list[1] = initDateFormat(lastDate)
return list
}