// 获取上周日期
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);
}
————————————————
版权声明:本文为优快云博主「羽墨诗韵」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/qq_41666251/article/details/130770297