2

I have an array with a date. When I parse it, the month increases by 1. How can I fix it?

var data = [{
  name: 'Arun',
  date: [2019, 4, 9, 14, 55, 28, 897778]
}, {
  name: 'Manohar',
  date: [2019, 4, 3, 22, 43, 54, 894553]
}]

data.forEach((item) => {
  item.date.pop()
  item.date = new Date(...item.date).toLocaleString('en-US')
});

console.log(data)

I want the month as April and not May. Please advice.

2 Answers 2

3

As per the documentation suggests, the monthIndex would start at 0, rather than 1. So you need to manually subtract 1.

data.forEach((item) => {
  item.date.pop()
  item.date[1]--
  item.date = new Date(...item.date).toLocaleString('en-US')
});
Sign up to request clarification or add additional context in comments.

3 Comments

How to reduce the month value in the loop I have?
Thanks. Appreciate the help. Just curious whether this Will convert from January 2019 to December 2018?
Yes, it will. But considering the source of your data should only be returning months between 1 and 12, the monthIndex will only ever be between 0 and 11. You could add a check if you wanted to.
0

The month is represented by a value from 0 to 11, 4 is the fifth month, it corresponds to May, you just need to decrease it by 1.

1 Comment

How to reduce the month value in the loop I have?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.