Geoff
Geoff

Reputation: 6639

Moment js add date and format fails

I would like to add days to a specific date and format the output. So I have the following:

addDays(date){
    return  moment(date).add(365, 'd').format("DD/MM/YYYY");
}

I have tested the above with the following

console.log(addDays("24/05/2021")) //this returns invalid date
console.log(addDays("05/06/2021")) //returns 06/05/2022

In the first date it returns invalid date and the second one I expected it to return 05/06/2022 but it returns the wrong date.

What am I missing for this to work. My dates are in the format dd/mm/yyyy

Upvotes: 0

Views: 158

Answers (3)

0stone0
0stone0

Reputation: 43983

It's failing because momentjs can't parse that date.

You'll have to specify the format your passing:

moment(inputDate, 'DD/MM/YYYY')

MomentJS String + Format documentation


Please see below example which will the expected output:

function addDays(inputDate){
  return moment(inputDate, 'DD/MM/YYYY').add(365, 'd').format("DD/MM/YYYY");
}
 
console.log(addDays("24/05/2021"));
console.log(addDays("05/06/2021"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

24/05/2022
05/06/2022

That said, I'd still recommend using moment().add(1, 'year'):

function addDays(inputDate){
  return moment(inputDate, 'DD/MM/YYYY').add(1, 'year').format("DD/MM/YYYY");
}

function addDays(inputDate){
  return moment(inputDate, 'DD/MM/YYYY').add(1, 'year').format("DD/MM/YYYY");
}
 
console.log(addDays("24/05/2021"));
console.log(addDays("05/06/2021"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Upvotes: 2

Utmost Creator
Utmost Creator

Reputation: 1121

You could do this in 2 way: Using day and year

let addNYears = function(years = 1, date) {
  return moment(date, 'DD/MM/YYYY').add(years, 'year').format("DD/MM/YYYY");
}

let addNDays = function(days = 1, date) {
  return moment(date, 'DD/MM/YYYY').add(days, 'day').format("DD/MM/YYYY");
}

console.log(addNYears(1, new Date())); // +1 year
// this is not the best way as each 4 years we have a leap year.
console.log(addNDays(365, new Date())); // +365 days
console.log(addNDays(5, new Date())); // +5 days
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Upvotes: 0

Steve -Cutter- Blades
Steve -Cutter- Blades

Reputation: 5432

Does it? If you really want to add a year then .add(1, 'year'), not 365 days.

Upvotes: 1

Related Questions