Search code examples
javascriptreactjsecmascript-6momentjsmoment-timezone

UTC Date Time to Full Date in ES6


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')}


Solution

  • 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.