Search code examples
javascriptdestructuring

Extract day, month, year from a YYYY-DD-MM string in Javascript


I am finding the best solution for extracting day, month, year from string with YYYY-DD-MM in Javascript:

Extract from:

2019-25-01

To object:

{ day: 25, month: 01, year: 2019 }

What is the best way to do it. Thank in advance!


Solution

  • You could split, destructure and return a new object.

    const getDate = string => (([year, day, month]) => ({ day, month, year }))(string.split('-'));
    
    console.log(getDate('2019-25-01'));