1. 控件作用
该控件用于计算从当前日期 间隔的天数,获取本周日期,本月日期、以及本月的天数
(function(window){
var My_dates = {
/**
* 获取本周、本季度、本月、上月的开始日期、结束日期、以及本月的天数
*/
createNew: function(){
var myDate = {};
myDate.now = new Date();
myDate.nowDayOfWeek = myDate.now.getDay()-1; //今天本周的第几天
myDate.nowDay = myDate.now.getDate(); //当前日
myDate.nowMonth = myDate.now.getMonth(); //当前月
myDate.nowYear = myDate.now.getYear(); //当前年
myDate.nowYear += (myDate.nowYear < 2000) ? 1900 : 0; //
//格式化日期:yyyy-MM-dd
myDate.formatDate = function(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);
};
//获取AddDayCount天后的日期 AddDayCount INT
myDate.GetTargetDate = function(AddDayCount) {
var dd = new Date();
dd.setDate(dd.getDate()+AddDayCount);
return myDate.formatDate(dd);
},
//获取当前月的天数
myDate.getMonthDays = function() {
var monthStartDate = new Date(myDate.nowYear, myDate.nowMonth, 1);
var monthEndDate = new Date(myDate.nowYear, myDate.nowMonth + 1, 1);
var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
return days;
};
//获得本周的开始日期
myDate.getWeekStartDate= function() {
var weekStartDate = new Date(myDate.nowYear, myDate.nowMonth, myDate.nowDay - myDate.nowDayOfWeek);
return this.formatDate(weekStartDate);
};
//获得本周的结束日期
myDate.getWeekEndDate = function() {
var weekEndDate = new Date(myDate.nowYear, myDate.nowMonth, myDate.nowDay + (6 - myDate.nowDayOfWeek));
return this.formatDate(weekEndDate);
};
//获得本月的开始日期
myDate.getMonthStartDate = function() {
var monthStartDate = new Date(myDate.nowYear, myDate.nowMonth, 1);
return this.formatDate(monthStartDate);
};
//获得本月的结束日期
myDate.getMonthEndDate = function() {
var monthEndDate = new Date(myDate.nowYear, myDate.nowMonth, myDate.getMonthDays(myDate.nowMonth));
return this.formatDate(monthEndDate);
};
return myDate;
}
};
window.my_dates = My_dates.createNew();
})(window);
2. 使用方式
- 计算最近七天
my_dates.GetTargetDate(-6); - 计算本周开始日期
my_dates.getWeekStartDate();
3.本周的结束日期
my_dates.getMonthEndDate ();
4 .日期格式化(yyyy-mm-dd)
my_dates.formatDate(new Date());