效果图
直接放代码
class DateUtil {
constructor() {
this.now = new Date(); // 当前日期
this.nowDayOfWeek = this.now.getDay(); // 今天本周的第几天
this.nowDay = this.now.getDate(); // 当前日
this.nowMonth = this.now.getMonth(); // 当前月
this.nowYear = this.now.getYear(); // 当前年
this.nowYear += (this.nowYear < 2000) ? 1900 : 0;
}
/**
* 获得当前日期
*
* @returns
*/
getNowDay() {
return this.formatDate(new Date());
}
/**
* 获得本周的开始时间
*
* @returns
*/
getStartDayOfWeek() {
var day = this.nowDayOfWeek || 7;
return this.formatDate(new Date(this.now.getFullYear(), this.nowMonth, this.nowDay + 1 - day));
}
/**
* 获得本周的结束时间
*
* @returns
*/
getEndDayOfWeek() {
var day = this.nowDayOfWeek || 7;
return this.formatDate(new Date(this.now.getFullYear(), this.nowMonth, this.nowDay + 7 - day));
}
getThirtyDay() {
// 过去30天
let Thirty = this.now.getTime() - 24 * 60 * 60 * 1000 * 30
return { start: this.formatDate(new Date(Thirty)), end: this.formatDate(this.now) }
}
// 本周
getCurrentWeek() {
return { start: this.getStartDayOfWeek(), end: this.getEndDayOfWeek() };
}
// 上周
getStartDayOfTwoWeek() {
let a = new Date(this.getStartDayOfWeek()).getTime() - 24 * 60 * 60 * 1000 * 7
let b = new Date(this.getEndDayOfWeek()).getTime() - 24 * 60 * 60 * 1000 * 7
return { start: this.formatDate(new Date(a)), end: this.formatDate(new Date(b)) };
}
// 本月
getCurrentMonth() {
return { start: this.getStartDayOfMonth(), end: this.getEndDayOfMonth() }
}
// 上月
getLastMonth() {
let a = new Date(this.getStartDayOfMonth()).getTime() - 24 * 60 * 60 * 1000 * this.getMonthDays()
let b = new Date(this.getEndDayOfMonth()).getTime() - 24 * 60 * 60 * 1000 * this.getMonthDays()
return { start: this.formatDate(new Date(a)), end: this.formatDate(new Date(b)) };
}
/**
* 获得本月的开始时间
*
* @returns
*/
getStartDayOfMonth() {
var monthStartDate = new Date(this.nowYear, this.nowMonth, 1);
return this.formatDate(monthStartDate);
}
/**
* 获得本月的结束时间
*
* @returns
*/
getEndDayOfMonth() {
var monthEndDate = new Date(this.nowYear, this.nowMonth, this.getMonthDays());
return this.formatDate(monthEndDate);
}
/**
* 获得本月天数
*
* @returns
*/
getMonthDays() {
var monthStartDate = new Date(this.nowYear, this.nowMonth, 1);
var monthEndDate = new Date(this.nowYear, this.nowMonth + 1, 1);
var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
return days;
}
/**
* @param 日期格式化
* @returns {String}
*/
formatDate(date) {
var myyear = date.getFullYear();
var mymonth = date.getMonth() + 1;
var myweekday = date.getDate();
if (mymonth < 10) {
mymonth = "0" + mymonth;
}
if (myweekday < 10) {
myweekday = "0" + myweekday;
}
return (myyear + "-" + mymonth + "-" + myweekday);
}
};
var util = new DateUtil()
console.log('最近30天',util.getThirtyDay())
console.log('本月',util.getCurrentMonth())
console.log('上月',util.getLastMonth())
console.log('本周',util.getCurrentWeek())
console.log('上周',util.getStartDayOfTwoWeek())