获取上一周/上个月 的开始时间与结束时间

// 获取上周日期
function lastWeek() {
	//获取今天
	let nowDate = new Date(); //当天日期
	//今天是本周的第几天
	let nowDayOfWeek = nowDate.getDay();
	//当前日
	let nowDay = nowDate.getDate();
	//当前月
	let nowMonth = nowDate.getMonth();
	//当前年
	let nowYear = nowDate.getFullYear();
	//获得上周的开始日期
	let getUpWeekStartDate = formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7), 'Y-MM-dd');
	//获得上周的结束日期
	let getUpWeekEndDate = formatDate(new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek - 7)), 'Y-MM-dd');
	return [getUpWeekStartDate, getUpWeekEndDate]
}

//获得某月的天数
function getMonthDays(myMonth){
	let nowDate = new Date(); //当天日期
	let nowYear = nowDate.getFullYear();
	var monthStartDate = new Date(nowYear, myMonth, 1);
	var monthEndDate = new Date(nowYear, myMonth + 1, 1);
	var days = (monthEndDate - monthStartDate)/(1000 * 60 * 60 * 24);
	return days;
}

// 获取上个月日期
function lastMonth() {
	let lastMonthDate = new Date(); //上月日期
	lastMonthDate.setDate(1);
	lastMonthDate.setMonth(lastMonthDate.getMonth()-1);
	let lastMonth = lastMonthDate.getMonth();
	//获得上月开始时间
	 let getLastMonthStartDate = formatDate(new Date(new Date().getFullYear(), lastMonth, 1), 'Y-MM-dd');
	 //获得上月结束时间
	 let getLastMonthEndDate = formatDate(new Date(new Date().getFullYear(), lastMonth, this.getMonthDays(lastMonth)), 'Y-MM-dd');
	return [getLastMonthStartDate, getLastMonthEndDate]
}

// 日期格式化
function formatDate(data, fmt) {
	data = new Date(data)
	if (/(y+)/.test(fmt)) {
		fmt = String(fmt).replace(RegExp.$1, (data.getFullYear() + '').substr(4 - RegExp.$1.length));
	}
	let o = {
		'Y+': data.getFullYear(),
		'M+': data.getMonth() + 1,
		'd+': data.getDate(),
		'h+': data.getHours(),
		'm+': data.getMinutes(),
		's+': data.getSeconds()
	};

	// 遍历这个对象
	for (let k in o) {
		if (new RegExp(`(${k})`).test(fmt)) {
			let str = o[k] + '';
			fmt = String(fmt).replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
		}
	}
	return fmt;
}

// 日期补0
function padLeftZero(str) {
	return ('00' + str).substr(str.length);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值