Get the first and last date of the previous month in JQuery

前端 未结 7 822
攒了一身酷
攒了一身酷 2021-02-09 07:41

I have this script,

 var today = new Date();
 var dd = today.getDate();
 var ffffd = today.getDate()-1;
 var ffffdd = today.getDate()-2;

 var mm = today.getMonth()+         


        
7条回答
  •  时光取名叫无心
    2021-02-09 08:12

    Try this: get today's date and set date to 1 which will get first of the current month. Then set hour to -1 which will shift it to previous months last day. Then set day to 1 to get first day of previous month.

    var today = new Date();
    var dd = today.getDate();
    
    today.setDate(1); // going to 1st of the month
    today.setHours(-1); // going to last hour before this date even started.
    var lastDay = today.toLocaleDateString('en-GB', {  
                                  year: 'numeric',
                                  month: 'numeric',
                                  day: 'numeric'
                              }).split(' ').join('-');
    
    alert("last day of previous month " + lastDay);
    
    today.setDate(1); // going to 1st of the previous month
    
    var firstDay = today.toLocaleDateString('en-GB', {  
                                  year: 'numeric',
                                  month: 'numeric',
                                  day: 'numeric'
                              }).split(' ').join('-');
    
    alert("first day of previous month " + firstDay);
    

    JSFiddle Demo

提交回复
热议问题