Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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');
like image 244
Bish25 Avatar asked Mar 31 '17 08:03

Bish25


People also ask

How do you add one day to a moment date?

To add time, pass the key of what time you want to add, and the amount you want to add. moment(). add(7, 'days');

How do you find the first day of year using moment?

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().

How do I set the date format in moments?

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.

How do you get the first and last day of the current week in this moment?

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.


1 Answers

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>
like image 136
VincenzoC Avatar answered Oct 15 '22 20:10

VincenzoC