I need to calculate a JS date given year=2014 and month=9 (September 2014).
I tried this:
var moment = require('moment');
var startDate = moment( year+'-'+month+'-'+01 + ' 00:00:00' );
var endDate = startDate.endOf('month');
console.log(startDate.toDate());
console.log(endDate.toDate());
Both of logs show:
Tue Sep 30 2014 23:59:59 GMT+0200 (CEST)
Tue Sep 30 2014 23:59:59 GMT+0200 (CEST)
End date is correct but... why the start date is not?
doc
Try the following code:
The following code should work:
When you use
.endOf()
you are mutating the object it's called on, sostartDate
becomes Sep 30You should use
.clone()
to make a copy of it instead of changing itThat's because
endOf
mutates the original value.Relevant quote:
Here's an example function that gives you the output you want:
References:
endOf()
clone()
Date from object