Find first day of previous month in javascript

前端 未结 5 1767
一生所求
一生所求 2020-12-05 23:16

Given a date object, how to get its previous month\'s first day in javascript

5条回答
  •  情话喂你
    2020-12-05 23:41

    I like this solution. It might not be the briefest, but it highlights some functions of the setDate() method on Date() objects that not everybody will be familiar with:

    function firstDayPreviousMonth(originalDate) {
        var d = new Date(originalDate);
        d.setDate(0); // set to last day of previous month
        d.setDate(1); // set to the first day of that month
        return d;
    }
    

    It makes use of the fact that .setDate(0) will change the date to point to the last day of the previous month, while .setDate(1) will change it (further) to point to the first day of that month. It lets the core Javascript libs do the heavy lifting.

    You can see a working Plunk here.

提交回复
热议问题