Bish25
Bish25

Reputation: 616

Setting the day of the date to the 1st with moment.js

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:

My code:

var startDate = moment(date).subtract(1,'months')
var endDate = moment(date).add(1,'months');

Upvotes: 6

Views: 15584

Answers (3)

VincenzoC
VincenzoC

Reputation: 31482

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>

Upvotes: 19

Monisha
Monisha

Reputation: 113

let startDate = moment().startOf('month').subtract(1, 'months').toDate()
let endDate = moment().endOf('month').add(1, 'months').toDate()

Upvotes: 1

Andrii Komarnitskyi
Andrii Komarnitskyi

Reputation: 120

You can use moment().startOf('month') and moment().endOf('month') methods

Upvotes: 2

Related Questions