简体   繁体   中英

Format toUTCString as toLocaleString

How can I convert a UTC string as seen below to something like July, 31 2020?

const date = '2020-07-31'
const utc = new Date(date).toUTCString();

So instead of Fri, 31 Jul 2020 00:00:00 GMT, I would like July, 31 2020/

moment is good to use for handling date and time.

moment('2020-07-31').format('MMMM, DD yyyy')

Luxon is good for an alternative moment since they recommend to use it ;).

DateTime.local().toLocaleString(DateTime.DATE_FULL);

This method relies on just the Date object and basic string methods.

 const date = '2020-07-31' const utc = new Date(date).toUTCString(); function changeDate(str) { var months = { Jan: 'January', Feb: 'Febuary', Mar: 'March', Apr: 'April', May: 'May', Jun: 'June', Jul: 'July', Aug: 'August', Sep: 'September', Oct: 'October', Nov: 'November', Dec: 'December', } var str2 = new Date(str).toLocaleString() str2 = str2.split(/,/)[0].split(/\\//g) str2 = months[str.split(/,/)[1].trim().split(/ /g)[1]] + ', ' + str.split(/,/)[1].trim().split(/ /)[0] + ' ' + str.split(/ /)[3] return str2 } console.log(changeDate(utc))

Not sure why everyone else is making it complicated. Instead of using toUTCString, simply use new Date(date).toDateString()

  const formatSelectedDate = (date) => {
    const utcDayDateTime = new Date(date).toUTCString();
    const utcDateTime = utcDayDateTime.split(',')[1];
    const splitUtcDateTime = utcDateTime.split(' ');
    const month = splitUtcDateTime[2];
    const day = splitUtcDateTime[1];
    const year = splitUtcDateTime[3];
    return `${month}, ${day} ${year}`;
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM