ilyo
ilyo

Reputation: 36391

Getting first day of month without changing the Moment object

I want to get the first day of a month, and then do other stuff with the Moment date object, but what happens is that when I do

moment().startOf('month').day()

It changes the day of the moment object to the first day of month, instead of simply reading it

var m = moment()
m.format('D') // 20
m.startOf('month').day()
m.format('D') // 1

Can I only read the first day, without changing the moment object?

Upvotes: 2

Views: 987

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

Can I only read the first day, without changing the moment object?

I don't think you can, but you can clone it first. So assuming m is a Moment object you don't want to change:

    m.clone().startOf('month').day();
//   ^^^^^^^^

Example:

var m = moment("2016-06-20", "YYYY-MM-DD");
console.log(m.format("dddd Do"));                          // Monday 20th
console.log(m.clone().startOf('month').format("dddd Do")); // Wednesday 1st
// ----------^^^^^^^^
console.log(m.format("dddd Do"));                          // Monday 20th
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

Upvotes: 3

Related Questions