rochellecanale
rochellecanale

Reputation: 149

How can I get the first day of next month using Angular and Moment

We have a problem regarding the generated logs on our application. And the solution is we need to get the first day of the next month even if the selected day is on the middle of the month.

Tried to read docs on Moment but I couldn't found any possible solution.

var currentDate = new Date();
var start_date = new Date(); //Wed Jun 05 2019 13:23:06 GMT+0800 (Philippine Standard Time)

console.log(start_date);

start_date.setDate(start_date.getDate() - 365); //1496640186958

console.log(start_date.setDate(start_date.getDate() - 365)); //Monday, June 5, 2017 1:23:06.958 PM GMT+08:00
// this output should be July 1, 2017, how can I get the first day of next month here?

start_date = customizeDate.formatDateToString(start_date);
var end_date = dateRange.endDate;

Upvotes: 3

Views: 7974

Answers (4)

wentjun
wentjun

Reputation: 42526

You can do it with Vanilla JavaScript. Do note that I have added the if statement to check if the month of the current Date is December. This is to prevent any issues whereby the month will 'overflow' to 12.

const today = new Date(); 
let next;
if (today.getMonth() === 11) {
  next = new Date(today.getFullYear() + 1, 0, 1);
} else {
    next = new Date(today.getFullYear(), today.getMonth() + 1, 1);
}

console.log(next);

Upvotes: 2

Hien Nguyen
Hien Nguyen

Reputation: 18975

You can use this with your custom format

const startOfNextMonth = moment().add(1, 'M').startOf('month').format('YYYY-MM-DD hh:mm:ss');

const startOfNextMonth = moment().add(1, 'M').startOf('month').format('YYYY-MM-DD hh:mm:ss');
console.log(startOfNextMonth);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

Upvotes: 9

JossFD
JossFD

Reputation: 2216

Here's a possible approach, creating a new date object then adding 1 to the month and finally setting the day to the 1st:

start_date = new Date(start_date.getFullYear(), start_date.getMonth() + 1, 1);

Stackblitz

Upvotes: 0

rochellecanale
rochellecanale

Reputation: 149

Ok I managed to solve it using this chain of function:

console.log(moment(1496640186958).add(1, 'months').startOf('month').format('ll'));

Upvotes: 0

Related Questions