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?
CodePudding user response:
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));
CodePudding user response:
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