Javascript - Get Previous Months Date

后端 未结 6 899
情深已故
情深已故 2021-02-14 12:25

If i have a variable that returns a date, in the format of dd MMM yyyy, so 28 Aug 2014, how can i get the date of the previous month.

I can modify the month via:

6条回答
  •  北恋
    北恋 (楼主)
    2021-02-14 13:17

    This returns all previous months with the beginning and end of the month

         var now = new Date();
                var start_month = new Date();
                start_month.setMonth(now.getMonth() - 5);
                for (var d = start_month; d <= now; d.setMonth(d.getMonth() + 1)) {
                    var firstDay = new Date(d.getFullYear(), d.getMonth(), 1);
                    var x = new Date(firstDay);
                    x.setDate(0);
                    x.setDate(1);
    
                    var date = new Date(x);
                    var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
                    var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
    
                    var startDate = `${firstDay.getFullYear()}-${firstDay.getMonth() + 1}-${firstDay.getDate()}`;
                    var endDate = `${lastDay.getFullYear()}-${lastDay.getMonth() + 1}-${lastDay.getDate()}`;
                    console.log(startDate)
                    console.log(endDate)
                }
    

提交回复
热议问题