1

How can i convert this 2021-01-10 12:47:29 UTC to January 10, 2021?

I'm using this below using moment.js but this works browsers but not in Safari {moment(video?.createdAt).format('MMMM D, YYYY')}

Joseph
  • 7,042
  • 23
  • 83
  • 181
  • 1
    try this: `moment("2021-01-10 12:47:29 UTC","YYYY-MM-DD HH:mm:ssZ").format("MMMM D, YYYY")` – Rohit Khanna Jan 22 '21 at 04:55
  • @RohitKhanna. Thanks how about displaying the time? I tried displaying the time, its wrong. Its outputting 12:47 PM. It should be 8:47 PM. `moment(video?.createdAt, "YYYY-MM-DD HH:mm:ssZ").format('h:mm A z')` – Joseph Jan 22 '21 at 05:02
  • 2
    On a side note, moment is deprecated https://momentjs.com/docs/#/-project-status/ – Akshay Jan 22 '21 at 05:57

3 Answers3

1

Moment.js is deprecated. Here's an alternative using native JS features.

First we need to convert the date string into a Date object. Calling new Date(video?.createdAt) is not reliable as mentioned on the Date() constructor page on MDN:

Parsing of date strings with the Date constructor (and Date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies.

See Date Time String Format on MDN for reference of the correct format. For example:

// This expects inputs in the form of
// `2021-01-10 12:47:29 UTC`
function parseDate(dateString) {
  const [date, time] = dateString.split(' ')
  return new Date(`${date}T${time}.000Z`) // Z = UTC
}

Then we can use Date.prototype.toLocaleString() to format the Date object:

// This expects inputs in the form of
// `2021-01-10 12:47:29 UTC`
function parseDate(dateString) {
  const [date, time] = dateString.split(' ')
  return new Date(`${date}T${time}.000Z`) // Z = UTC
}

function format(dateString) {
  if (!dateString) return 'some fallback value'

  const date = parseDate(dateString)
  return date.toLocaleString('en', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
  })
}

console.log(format('2021-01-10 12:47:29 UTC'))
//=> January 10, 2021, 2:47 PM

console.log(format(undefined))
//=> some fallback value

See Intl.DateTimeFormat() for all possible options. For example, these options produce slightly different results:

return date.toLocaleString('en', {
  dateStyle: 'long',
  timeStyle: 'short',
})

format('2021-01-10 12:47:29 UTC')
//=> January 10, 2021 at 2:47 PM

If the date strings can be in various formats, you probably need more robust date parsing. Or if you need exotic formattings, toLocaleString() might not meet your needs. In those cases, it might be useful to use one of the recommended Moment.js alternatives.

Matias Kinnunen
  • 7,828
  • 3
  • 35
  • 46
0

The new Intl DateTimeFormat API is gaining more support natively in many browsers, so it is a more future proof solution. As suggested in the doc, you can use polyfills for browsers which lack full support of this feature. Unfortunately, Safari is one of the browser which is yet to catch up.

A short snippet to achieve what you are looking for would be

new Intl.DateTimeFormat('en-US', { dateStyle: 'long'}).format(new Date("2021-01-10 12:47:29Z"))  // outputs January 10, 2021

Keep in mind that date time string without Z at the end would be parsed as local time. Z means the date time supplied is UTC.

Tianzhen Lin
  • 2,404
  • 1
  • 19
  • 19
  • this is the value the real value not the one with z `2021-01-10 12:47:29 UTC` – Joseph Jan 22 '21 at 06:03
  • Its displaying RangeError: Invalid time value – Joseph Jan 22 '21 at 06:10
  • The error is expected in Safari, you can include the [polyfills](https://formatjs.io/docs/polyfills/intl-datetimeformat/) which should patch the browser. Overtimes the polyfills can be dropped when more browsers implement this API. – Tianzhen Lin Jan 22 '21 at 18:50
0

If you're searching for moment.js alternative, I would suggest date-fns. Here is a blog post that compares the 2 of them.

Here is the format documentation for date-fns.

So to answer your question using date-fns:

format(new Date(video?.createdAt), 'MMMM D, YYYY')
I am L
  • 4,288
  • 6
  • 32
  • 49
  • date-fns is nice. [MDN says](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#Timestamp_string) that "Parsing of date strings with the `Date` constructor (and `Date.parse()`, which works the same way) is _strongly discouraged_ due to browser differences and inconsistencies." – Matias Kinnunen Jan 22 '21 at 06:48
  • @mtsknn I thought they discourage it because the string value doesn't have a timezone and is treated differently by diff browsers because of that local-tz inconsistency(?) In OP's case the date string he provided has a 'UTC', so should be good right? – I am L Jan 22 '21 at 07:10
  • `new Date('2021-01-10 12:47:29 UTC')` produces "Invalid Date" on Firefox and iOS Safari. Seems to work on Chrome. Dunno about other browsers. – Matias Kinnunen Jan 22 '21 at 07:13