2

How can I convert a day like 2020-05-01 to 5/1/2020 in one line.

I tried this but I wasn't able to remove the zero's nor I could arrange them in correct order.

('2020-05-01').split('-').reverse().join('/')

3
  • '2020-05-01'.split('-').reduceRight((arr, str) => arr.concat(Number(str)), []).join('/') Commented Feb 22, 2021 at 20:47
  • or with "unary plus" operator ... '2020-05-01'.split('-').reduceRight((arr, str) => arr.concat(+str), []).join('/') Commented Feb 22, 2021 at 21:13
  • Why the single line requirement? Commented Feb 22, 2021 at 22:00

2 Answers 2

2

Use .map to iterate and Number to convert:

console.log(
  ('2020-05-01')
    .split('-')
    .map(Number) // add this
    .reverse()
    .join('/')
);

Sign up to request clarification or add additional context in comments.

4 Comments

is there any way to convert 2020-05-01 to 5/1/2020(month/date/year) in one line?
@ArpitFalcon you can do it in moment as follows: moment('2020-05-01').format('M/D/YYYY')
'2020-05-01'.replace((/(\d{4})-(\d{2})-(\d{2})/g), (_, y, m, d) => [m, d, y].join('/'))
of cause I forgot converting month and day into single digits where possible; one can make use of the "unary plus" operator and the above example changes to ... '2020-05-01'.replace((/(\d{4})-(\d{2})-(\d{2})/g), (_, y, m, d) => [+m, +d, y].join('/'))
1
const event = new Date('2020-05-01');
console.log((event.getMonth() + 1) + "/" + event.getDate() + "/" + event.getFullYear());

2 Comments

cheating ... its not in a single line ... ;-)
This is the right answer. Dates aren't strings, and treating them that will will just break later in unexpected ways.

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.