sushmita
sushmita

Reputation:

Find first day of previous month in javascript

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

Upvotes: 42

Views: 62717

Answers (6)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59436

Why reinventing the wheel?

Use moment.js or one of the alternatives (Luxon, Day.js, etc.):

moment().subtract(1, "months").startOf("months").toDate().

Upvotes: 1

Coder
Coder

Reputation: 253

It will help to get the previous month first and last date.

    function getLastMonth(){
        var now = new Date();
        var lastday  = new Date(now.getFullYear(), now.getMonth(), 0);
        var firstday = new Date(lastday.getFullYear(), lastday.getMonth(), 1);
        var lastMonth = firstday.getDate()+'/'+(firstday.getMonth()+1)+'/'+firstday.getFullYear()+' - '+lastday.getDate()+'/'+(firstday.getMonth()+1)+'/'+lastday.getFullYear();
        return lastMonth;
    }

Upvotes: 7

Hillsie
Hillsie

Reputation: 715

I've needed to use the begging of the month in a BootStrap Min month and didn't want to write it all out.

(() => new Date(new Date().getFullYear(), new Date().getMonth(),1, 0))()

Upvotes: 0

Michael Oryl
Michael Oryl

Reputation: 21642

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.

Upvotes: 12

Prestaul
Prestaul

Reputation: 85137

function firstDayInPreviousMonth(yourDate) {
    var d = new Date(yourDate);
    d.setDate(1);
    d.setMonth(d.getMonth() - 1);
    return d;
}

EDIT: Alright... I've definitely learned something here. I think that this is the simplest solution that covers all cases (and yes, it does work for January):

function firstDayInPreviousMonth(yourDate) {
    return new Date(yourDate.getFullYear(), yourDate.getMonth() - 1, 1);
}

Upvotes: 55

paxdiablo
paxdiablo

Reputation: 881113

The following should work:

now = new Date();
if (now.getMonth() == 0) {
    current = new Date(now.getFullYear() - 1, 11, 1);
} else {
    current = new Date(now.getFullYear(), now.getMonth() - 1, 1);
}

keeping in mind that months are zero-based so December is 11 rather than 12.

But, as others have pointed out, the month wraps, even as part of the atomic constructor, so the following is also possible:

now = new Date();
firstDayPrevMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);

Upvotes: 16

Related Questions