JavaScript for getting the previous Monday

后端 未结 7 2101
孤城傲影
孤城傲影 2021-02-19 04:03

I would like for the previous Monday to appear in the field where a user enters today\'s date.

E.g.: If today\'s date is entered 29-Jan-16 t

7条回答
  •  长情又很酷
    2021-02-19 05:05

    The easiest solution is to go back the number of days based on today's date. For example, if today's day(0) is Sunday, you can go back 6 days to find the previous Monday. If Today is Monday, you can go back 7 days. Therefore using a modulo will help you in this scenario simply because the number of days you will need to go back is %7 plus 6. Let me break it down in simple steps.

    var today=new Date();
    

    This will give you today's date. Now,

    var todaysDay=today.getDay();
    

    This will give you your day starting with zero.

    var goBack=today.getDay()%7+6;
    

    Now, declare a new date.

    var lastMonday=new Date().setDate(today.getDate()-goBack);
    

    Now, this will give you a numeric date value. Convert it back to Date

    var desiredDate=new Date(lastMonday);
    

提交回复
热议问题