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:
21/05/2017
01/04/2017
30/06/2017
My code:
var startDate = moment(date).subtract(1,'months')
var endDate = moment(date).add(1,'months');
To add time, pass the key of what time you want to add, and the amount you want to add. moment(). add(7, 'days');
moment(). startOf('year'); // set to January 1st, 12:00 am this year moment(). startOf('month'); // set to the first of this month, 12:00 am moment(). startOf('quarter'); // set to the beginning of the current quarter, 1st day of months, 12:00 am moment().
moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format. This example formats a date as a four-digit year, followed by a hyphen, followed by a two-digit month, another hyphen, and a two-digit day.
If it's not 0, simply subtract that many days (Moment has functions for adding and subtracting days from a date) from the current date, and then you'll have the first day of the week. Once you have the first day of the week, add 6 days to that and you'll have the last day of the week.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With