当前位置:   article > 正文

JS获取上周(自然周、最近七天)、上月(自然月、最近一个月)、全年的开始和结束日期_js获取近近一周 近一个月时间

js获取近近一周 近一个月时间

JS获取上周(自然周、最近七天)、上月(自然月、最近一个月)、全年的开始和结束日期

let now = new Date(); 
let nowTime = now.getTime(); //当前的时间戳
let nowYear = now.getFullYear(); //当前年
let weekDay = now.getDay(); //当前星期
let lastMonth = now.getMonth(); //上一个月
let oneDayTime = 24 * 3600* 1000; //一天的总毫秒数
let start = "";  //开始日期
let end = "";  //结束日期
let myDate  = []  //最终需要的日期数组 [开始,结束]

// 1. 上周(最近七天)
let week = nowTime - oneDayTime * 7;  // oneDayTime * 7 代表一周的总毫秒(ms)数
start = now.setTime(week);
end = new Date();
myDate = [formatDate(start), formatDate(end)];
//console.log(myDate , "最近七天");

// 2. 上周(自然周:周一到周日)
start = nowTime - (weekDay + 6) * oneDayTime; //上周一的时间戳
end = nowTime - (weekDay + 0) * oneDayTime; //上周日的时间戳
myDate = [formatDate(start), formatDate(end)];
//console.log(myDate , "自然周-上周");

// 3. 上月(最近一个月) 
let mouth = nowTime - oneDayTime * 30;  //oneDayTime * 30 代表一个月的总毫秒数
start = now.setTime(mouth);
end = new Date();
myDate = [formatDate(start), formatDate(end)];
//console.log(myDate, "最近一个月");

// 4. 上月(自然月: 每月1号到月末)
/*
	*知识补充: new Date()第3个参数默认为1,就是每个月的1号; 当该参数为0 时,就是每个月的最后一天;
	*如:获取2022年一月份的天数:  new Date("2022","01",0).getDate()  //通过getDate()方法得到该月的天数,即31
*/
start = new Date(nowYear, lastMonth - 1, 1); //上一个月的第一天日期
end = new Date(nowYear, lastMonth, 0); //上一月的最后一天日期
myDate = [formatDate(start), formatDate(end)];
//console.log(myDate, "自然月-上月");

//格式化日期函数(最终格式yyyy-MM-dd)
function formatDate(date) {
  let myDate = new Date(date);
  let year = myDate.getFullYear();
  let month = myDate.getMonth() + 1;
  let weekday = myDate.getDate();
  if (month < 10) {
    month = "0" + month;
  }
  if (weekday < 10) {
    weekday = "0" + weekday;
  }
  return year + "-" + month + "-" + weekday;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/601896
推荐阅读
相关标签
  

闽ICP备14008679号