example of getDepart date format getDepart = 2022-04-29 desired result 29 APR, 2022 const getStringDepart = () => { const months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const departArray = getDepart.split("-"); const departDay = departArray[2]; const departYear = departArray[0]; const departMonth = ???????????? const departString = `${departDay} ${departMonth}, ${departYear}`; return departString; }
I’m trying to turn my YYYY-MM-DD string date format to a DD mon, YYYY
string.
I was thinking about using an array with the months and matching the month number to it’s index, but I can’t find a way to do so.
Advertisement
Answer
You just need to pass the month - 1
on your array. It should return the month properly.
getDepart = '2022-04-29'; const getStringDepart = () => { const months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const departArray = getDepart.split("-"); const departDay = departArray[2]; const departYear = departArray[0]; const departMonth = departArray[1]; const departString = `${departDay} ${months[Number(departMonth) - 1]}, ${departYear}`; return departString; } function test() { console.log(getStringDepart()) }