前幾天做OEM的需求,需要獲取當前時間往前 10 個小時、 10 天、10 周、 10月。方法如下:
// 格式化時間
/*
* date: 日期物件
* type: 格式化型別。引數有4種 'hour': 2018-03-07 19:00; 'day': 2018-03-07; 'week': 03-05 至 03-11; 'month': 2018-03
*/
function formattingDate(date, type) {
let year = date.getFullYear(),
month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1),
day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(),
hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
if (!type || type === 'day') { // 預設顯示年、月、日
return year + "-" + month + "-" + day;
} else if (type === 'hour') {
return year + "-" + month + "-" + day + " " + hour + ":00";
} else if (typ === 'week') {
return month + "-" + day;
} else if (type === 'month') {
return year + "-" + month;
}
}
複製程式碼
1、獲取當前時間往前 10 個小時
function getTenHour () {
let nowDateTime = new Date().getTime(),
noeHourTime = 60 * 60 * 1000,
hourArr = [];
for (var i = 0; i < 10; i++) {
let itemHourTime = nowDateTime - i * noeHourTime,
itemHour = formattingDate(new Date(itemHourTime), 'hour');
hourArr.push(itemHour);
}
return hourArr;
}
複製程式碼
2、獲取當前時間往前 10 天
function getTenDay () {
let nowDateTime = new Date().getTime();
noeDayTime = 24 * 60 * 60 * 1000,
dayArr = [];
for (var i = 0; i < 10; i++) {
let itemDayTime = nowDateTime - i * noeDayTime,
itemDay = formattingDate(new Date(itemDayTime), 'day');
dayArr.push(itemDay);
}
return dayArr;
}
複製程式碼
上面還是挺簡單的,就是用當前的毫秒數減去單位毫秒,然後初始化一個日期物件就好了。但是獲取周、月就麻煩了
3、獲取當前時間往前 10 周
function getTenWeek () {
let nowDate = new Date(),
nowDateTime = nowDate.getTime(),
noeDayTime = 24 * 60 * 60 * 1000,
nowDay = nowDate.getDay() === 0 ? 7 : nowDate.getDay(), // 獲取當前周幾。注意:週日的值為 0 ;
nowMondayTime = nowDateTime - (nowDay - 1) * noeDayTime, // 獲取當前所在周的週一
weekArr = [];
for (var i = 0; i < 10; i++) {
let itemMondayTime = nowMondayTime - i * 7 * noeDayTime, // 每個週一的毫秒數
itemMonday = formattingDate(new Date(itemMondayTime), 'week'),
itemWeekdayTime = nowMondayTime + i * 6 * noeDayTime, // 每個週日的毫秒數
itemWeekDay = formattingDate(new Date(itemWeekdayTime), 'week');
weekArr.push(itemMonday + ' 至 ' + itemWeekDay);
}
return weekArr;
}
複製程式碼
4、獲取當前時間往前 10 月
function getTenMonth () {
let nowDate = new Date(),
year = nowDate.getFullYear(),
month = nowDate.getMonth(),
nowMonthOneDay = new Date(year, month, 1), // 當前月的第一天
tempTime = nowMonthOneDay.getTime(),
oneDayTime = 24 * 60 * 60 * 1000,
monthArr = [];
for (var i = 0; i < 10; i++) {
let nowMonth = formattingDate(new Date(tempTime),'month'), // 當前月
prevMonthDate = new Date(tempTime - oneDayTime), // 上一個月的最後一天
prevYear = prevMonthDate.getFullYear(),
prevMonth = prevMonthDate.getMonth(),
prevMonthOneDay = new Date(prevYear, prevMonth, 1); // 上一個月的第一天
tempTime = prevMonthOneDay.getTime();
monthArr.push()
}
return monthArr;
}
複製程式碼