How can I convert a string date to an object?

Hi,

I have a date of

1980-01-01

I want to rewrite this as:

{
“year”: 1980,
“month”: 01,
“day”: 01
}

Hi @johnmbiddulph, you can first create a new Date() from the string and then get the desired values like so:

function toDateObject (value) {
  const date = new Date('1980-01-01')
 
  return {
    year: date.getFullYear(),
    month: date.getMonth() + 1, // month is from 0 - 11
    day: date.getDate()
  }
}

console.log(toDateObject('1980-01-01'))

(You might also just split the string by its hyphens, but parsing it with the built in API is certainly more versatile and robust.)

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.