Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
92 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65839486/utc-date-time-to-full-date-in-es6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...