js vue react get this week, this month, this season, the first day of the year

In today’s project, I want to get this week, this month, this season, and the first day of the year. I found that there are more or less problems with the online methods, so I wrote one myself, and it is available for personal testing.

  • Get the first day of the week, the first day of the month, the first day of the season, and the first day of the year of the specified date
  • @param date new Date() form, or new Date() with custom parameters
  • @returns The return value is a formatted date, yy-mm-dd

//Date formatting, the return value form is yy-mm-dd


function timeFormat(date) {
    
    
    if (!date || typeof(date) === "string") {
    
    
        this.error("参数异常,请检查...");
    }
    var y = date.getFullYear(); //年
    var m = date.getMonth() + 1; //月
    var d = date.getDate(); //日

    return y + "-" + m + "-" + d;
}

Get this week's Monday

function getFirstDayOfWeek (date) {
    
    

    var weekday = date.getDay()||7; //获取星期几,getDay()返回值是 0(周日) 到 6(周六) 之间的一个整数。0||7为7,即weekday的值为1-7

    date.setDate(date.getDate()-weekday+1);//往前算(weekday-1)天,年份、月份会自动变化
    return timeFormat(date);
}

//Get the first day of the month

function getFirstDayOfMonth (date) {
    
    
    date.setDate(1);
    return timeFormat(date);
}

//Get the first day of the season

function getFirstDayOfSeason (date) {
    
    
    var month = date.getMonth();
    if(month <3 ){
    
    
        date.setMonth(0);
    }else if(2 < month && month < 6){
    
    
        date.setMonth(3);
    }else if(5 < month && month < 9){
    
    
        date.setMonth(6);
    }else if(8 < month && month < 11){
    
    
        date.setMonth(9);
    }
    date.setDate(1);
    return timeFormat(date);
}

//Get the first day of the year

function getFirstDayOfYear (date) {
    
    
    date.setDate(1);
    date.setMonth(0);
    return timeFormat(date);
}

Looking for a job, no interview questions? Look here, scan the code to view 1000+ front-end interview questions

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/110200637