Javascript 处理时间大全
1. 获取从今天算起,几天后的日期
function GetDateStr(AddDayCount) {
var dd = new Date();
dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期
var y = dd.getFullYear();
var m = dd.getMonth() + 1;//获取当前月份的日期
var d = dd.getDate();
return y + "-" + m + "-" + d;
}
例如,我获取15天后的日期,就直接 GetDateStr(15); 即可得到。
2. 获取某个月份的天数
function getMonthDays(nowYear,myMonth) {
var monthStartDate = new Date(nowYear, myMonth-1, 1);
var monthEndDate = new Date(nowYear, myMonth, 1);
var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
return days;
}
传入需要年份和月份,就可以得到月的天数
3. 获取上个月的开始、结束日期
var days = getMonthDays(nowYear, nowMonth);
var strBeginTime = nowYear + "-" + (nowMonth) + "-" + "1";//上月第一天
var strEndTime = nowYear + "-" + (nowMonth) + "-" + days;//上月的最后一天
4. 获取上个季度时间段
//获得本季度的开端月份
function getQuarterStartMonth(nowMonth) {
var quarterStartMonth = 0;
if (nowMonth <= 3) {
quarterStartMonth = 1;
}
if (4 <= nowMonth && nowMonth <= 6) {
quarterStartMonth = 4;
}
if (7 <= nowMonth && nowMonth <= 9) {
quarterStartMonth = 7;
}
if (nowMonth >= 10) {
quarterStartMonth = 10;
}
return quarterStartMonth;
}
//以下就可以拼凑季度时间段
var startMonth = getQuarterStartMonth(nowMonth)-3;
var endMonth = startMonth + 2;
var endMonthDays = getMonthDays(nowYear, endMonth);
var strBeginTime = nowYear + "-" + startMonth + "-1";
var strEndTime = nowYear + "-" + endMonth + "-" + endMonthDays;