js獲取時間
獲取年余境、月著淆、日馋艺、周
格式化日期
獲取日期范圍
獲取歷史前N天的時間
獲取未來N天的時間
/**
* 自定義時間類
*/
class TimeClass {
constructor(date) {
if (!date || typeof (date) === "string") {
date = new Date();
}
this.date = date;
this.year = this.getCurrYear();
this.month = this.getCurrMonth();
this.day = this.getCurrDay();
this.week = this.getCurrWeek();
this.hours = this.getCurrHours();
this.minutes = this.getCurrMinutes();
this.seconds = this.getCurrSeconds();
}
/**
* 格式化時間
* @param date
* @returns {string}
*/
timeFormat(date) {
if (date) {
this.date = date;
}
return `${this.getCurrYear()}-${this.getCurrMonth()}-${this.getCurrDay()}`;
}
/**
* 獲取年份
* @returns {number}
*/
getCurrYear() {
return this.date.getFullYear();
}
/**
* 獲取月份
* @returns {*}
*/
getCurrMonth() {
let ominth = this.date.getMonth() + 1;
return ominth > 9 ? ominth : '0' + ominth;
}
/**
* 獲取本日
* @returns {any}
*/
getCurrDay() {
let oDay = this.date.getDate();
return oDay > 9 ? oDay : '0' + oDay;
}
/**
* 獲取周幾
* @returns {number}
*/
getCurrWeek() {
return this.date.getDay();
}
/**
* 獲取時
* @returns {number}
*/
getCurrHours() {
return this.date.getHours();
}
/**
* 獲取分
* @returns {number}
*/
getCurrMinutes() {
return this.date.getMinutes();
}
/**
* 獲取秒
* @returns {number}
*/
getCurrSeconds() {
return this.date.getSeconds();
}
/**
* 獲取本周開始日期
* @returns {string}
*/
getCurrWeekStart() {
var oWeek = this.getCurrWeek();
oWeek = oWeek > 0 ? oWeek : 7;
return this.computeTime(-oWeek + 1);
}
/**
* 獲取本周結(jié)束日期
* @returns {string}
*/
getCurrWeekEnd() {
var oWeek = this.getCurrWeek();
oWeek = oWeek > 0 ? oWeek : 7;
return this.computeTime(7 - oWeek);
}
/**
* 獲取本周日期范圍
* @returns {string[]}
*/
getCurrWeekScope() {
let startTime = this.getCurrWeekStart();
let endTime = this.getCurrWeekEnd();
return [startTime, endTime];
}
/**
* 獲取本月開始時間
* @returns {string}
*/
getCurrMonthStart() {
this.date.setDate(1);
console.log(this.date);
return this.timeFormat();
}
/**
* 獲取本月結(jié)束日期
* @returns {string}
*/
getCurrMonthEnd() {
var monthFirstDate = new Date(this.year, this.month, 1);
var oneDay = 1000 * 60 * 60 * 24;
this.date = new Date(monthFirstDate - oneDay);
console.log(this.date);
return this.timeFormat();
}
/**
* 獲取本月日期范圍
* @returns {string[]}
*/
getCurrMonthScope() {
let startTime = this.getCurrMonthStart();
let endTime = this.getCurrMonthEnd();
return [startTime, endTime];
}
/**
* 自定義加減天數(shù)
* @param num
* @returns {string}
*/
computeTime(num) {
this.date.setDate(this.date.getDate() + num);
return this.timeFormat();
}
}