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);
}
/**
* 获取本周结束日期
* @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();
}
/**
* 获取本月结束日期
* @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];
}
/**
* 自定义加减天数
* @param num
* @returns {string}
*/
computeTime(num) {
this.date.setDate(this.date.getDate() + num);
return this.timeFormat();
}
}
网友评论