0

I have a date value in my React app that's returned from MySQL as a string in this format:

"2012-03-04T00:00:00.000+00:00"

The date gets transformed, using moment, to this format:

03/04/2012

Using moment, this is simple:

moment(myDate).format('MM/DD/YYYY')

But I'd like to change this, since moment is no longer maintained.

Is there a simple way to do this transformation with some built-in javascript date function?

The answers here and here don't help here, as they include no details on formatting the resulting date the way I need it.

James Risner
  • 5,451
  • 11
  • 25
  • 47
Woodchuck
  • 3,869
  • 2
  • 39
  • 70
  • Have a look at [toLocaleDateString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString) No need for Moment. – Yogi Dec 06 '22 at 21:34
  • That gives me 3/4/2012,12:00:00 AM (after creating a new Date() from my string, then applying toLocaleDateString to it). – Woodchuck Dec 06 '22 at 22:27
  • I just tried it and the output is exactly what you asked for and with just one line of code: Demo [JSFiddle](https://jsfiddle.net/6adk79gs/) – Yogi Dec 06 '22 at 22:45
  • Thanks! I guess I needed the 'en-US'. But I would like to end up with 2 character MM and DD values. That's part of why I'm so confused as to why this question was immediately closed as a "duplicate". None of those other answers addresses this use case with that resulting format. – Woodchuck Dec 07 '22 at 05:01
  • 1
    See the updated [JSFiddle](https://jsfiddle.net/vtn50zjh/) for 2 character MM and DD. The method has many options to format the date however you want. – Yogi Dec 07 '22 at 08:29
  • 1
    That works great! If you're interested in creating this as an answer I would switch my accepted answer to this approach, as it's more straightforward than the one below. – Woodchuck Dec 07 '22 at 17:08

1 Answers1

1

You can use this:

const date = new Date("2019-08-01T00:00:00.000+00:00")
const year = date.getFullYear().toString().padStart(4, '0')
const month = (date.getMonth() + 1).toString().padStart(2, '0')
const day = date.getDate().toString().padStart(2, '0')
const formatted = `${month}/${day}/${year}`
console.log(formatted)

But I would just another library like date-fns or dayjs

Konrad
  • 21,590
  • 4
  • 28
  • 64
  • Thanks! This is what I needed. I’m stumped as to why this question was closed as a duplicate. None of the “duplicate” questions shows how to end up with this format. – Woodchuck Dec 07 '22 at 05:06