Setting the day of the date to the 1st with moment.js
13,543
Solution 1
Simply use add
and subtract
method to get next and previous month and startOf
and endOf
to get the first and the last day of the month.
Here a working sample:
var date = moment([2017, 4, 21]); // one way to get 21/05/2017
// If your input is a string you can do:
//var date = moment('21/05/2017', 'DD/MM/YYYY');
var startDate = date.clone().subtract(1, 'month').startOf('month');
var endDate = date.clone().add(1, 'month').endOf('month');
console.log(startDate.format('DD/MM/YYYY')); // 01/04/2017
console.log(endDate.format('DD/MM/YYYY')); // 30/06/2017
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Solution 2
You can use moment().startOf('month')
and moment().endOf('month')
methods
Solution 3
let startDate = moment().startOf('month').subtract(1, 'months').toDate()
let endDate = moment().endOf('month').add(1, 'months').toDate()
Comments
-
Bish25 over 1 year
I am looking through the moment documentation and can't find the the method required. In my solution I am getting today's date then getting the month before and the month after, but wish to get the very first day of the month and the very last day of the month ahead.
In brief this should be the out come:
- today's date:
21/05/2017
- startDate =
01/04/2017
- endDate =
30/06/2017
My code:
var startDate = moment(date).subtract(1,'months') var endDate = moment(date).add(1,'months');
- today's date: