Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...