简体   繁体   中英

How to get full day & month names from UTC date in JavaScript

I am trying to convert a date that's stored as a string in a JSON file into UTC string format using JavaScript.

Here is my JSON:

{
    "createdDate": {
        "utc": "2022-08-20T12:18:48.6588096Z",
        "local": "2022-08-20T12:18:48.6588096"
    }
}

Here is the function I am trying to use, but I'm not sure why it's displaying GMT:

let createdByUtc = new Date(resp.createdDate.utc).toUTCString()

Actual Result:

Sat, 20 Aug 2022 12:08:52 GMT

Required Result:

Saturday, August 20, 2022 at 12:08 PM UTC

Can someone please show me how I can get my createdByUtc variable in the required format?

Use a Intl.DateTimeFormat instance with a configuration for a UTC representation with appropriate date and time styles:

 const {format} = new Intl.DateTimeFormat('en-US', { timeZone: 'UTC', dateStyle: 'full', timeStyle: 'long' } ); // Example let dt = new Date("2022-08-20T12:18:48.6588096Z"); console.log(format(dt));

Try with defining some options like below.

let createdByUtc = JSON.parse( '{"utc": "2022-08-20T12:18:48.6588096Z", "local": "2022-08-20T12:18:48.6588096"}');
var newDate =new Date(createdByUtc.utc)

const options = {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour:'numeric',
  minute:'numeric'
};
options.timeZone = 'UTC';
options.timeZoneName = 'short';
console.log(newDate.toLocaleString('en-US', options))

//Saturday, August 20, 2022, 12:18 PM UTC

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