js获取本周/本月/本季的起始时间、结束时间及本月天数

2024年07月27日 建站教程

var now = new Date(); // 当前日期
var nowDayOfWeek = now.getDay(); // 今天是本周的第几天
var nowDay = now.getDate(); // 当前日
var nowMonth = now.getMonth(); // 当前月
var nowYear = now.getYear(); // 当前年
nowYear += (nowYear < 2000) ? 1900 : 0;
var getDate = {
  /*获得当前日期*/
  getNowDay() {
  	return this.formatDate(new Date());
  },
  /*获得本周的开始时间*/
  getStartDayOfWeek() {
  	var day = nowDayOfWeek || 7;
  	return this.formatDate(new Date(now.getFullYear(), nowMonth, nowDay + 1 - day));
  },
  /*获得本周的结束时间*/
  getEndDayOfWeek() {
  	var day = nowDayOfWeek || 7;
  	return this.formatDate(new Date(now.getFullYear(), nowMonth, nowDay + 7 - day));
  },
  /*获得本月的开始时间*/
  getStartDayOfMonth() {
  	var monthStartDate = new Date(nowYear, nowMonth, 1);
  	return this.formatDate(monthStartDate);
  },
  /*获得本月的结束时间*/
  getEndDayOfMonth() {
  	var monthEndDate = new Date(nowYear, nowMonth, this.getMonthDays());
  	return this.formatDate(monthEndDate);
  },
  /*获得本月天数*/
  getMonthDays() {
    var monthStartDate = new Date(nowYear, nowMonth, 1);
    var monthEndDate = new Date(nowYear, nowMonth + 1, 1);
    var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
    return days;
  },
  /*获得本季度开始*/
  getQuarterStart(){
    let m = 0;
    if(nowMonth<3>8){ //9 10 11
        m = 9
    }
    let quarterStart = new Date(nowYear,m,1)
    return this.formatDate(quarterStart)
  
  },
  /*获得本季度结束*/
  getQuarterEnd :function(){
    let m = 0;
    if(nowMonth<3>8){ //9 10 11
    	 m = 0
    }
    let quarterEnd = new Date(nowYear,m,1).getTime()-(60*60*24*1000)
    return this.formatDate(new Date(quarterEnd))
  },
  /*日期格式化*/
  formatDate(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);
  }
};
console.log('本周开始时间:',getDate.getStartDayOfWeek())
console.log('本周结束时间:',getDate.getEndDayOfWeek())
console.log('本月开始时间:',getDate.getStartDayOfMonth())
console.log('本月结束时间:',getDate.getEndDayOfMonth())
console.log('本月天数计算:',getDate.getMonthDays())
console.log('本季开始时间:',getDate.getQuarterStart())
console.log('本季结束时间:',getDate.getQuarterEnd())

本文链接:http://so.lmcjl.com/news/9255/

展开阅读全文
相关内容