乐闻世界logo
搜索文章和话题

How to convert a Date to UTC?

1个答案

1

In JavaScript, converting dates to UTC format can be achieved through multiple methods. Below, I will introduce several common methods with corresponding examples.

1. Using the toUTCString() Method of the Date Object

The toUTCString() method converts a date to a string representing Universal Coordinated Time (UTC). This is a straightforward method to obtain a UTC-formatted date string.

javascript
let date = new Date(); let utcDateString = date.toUTCString(); console.log(utcDateString);

Example

Assuming the time is 2023-03-14T12:00:00.000Z, using toUTCString() produces:

shell
Tue, 14 Mar 2023 12:00:00 GMT

2. Using the toISOString() Method

The toISOString() method returns a string representing the date in ISO 8601 format. The returned format is always UTC time, ending with Z to denote UTC.

javascript
let date = new Date(); let isoString = date.toISOString(); console.log(isoString);

Example

Continuing with the same date 2023-03-14T12:00:00.000Z, toISOString() returns:

shell
2023-03-14T12:00:00.000Z

3. Manually Calculating UTC Date

If you need other formats or more control, you can manually calculate the UTC date components.

javascript
let date = new Date(); let utcYear = date.getUTCFullYear(); let utcMonth = date.getUTCMonth() + 1; // getUTCMonth() returns months starting from 0, so +1 is added let utcDate = date.getUTCDate(); let utcHours = date.getUTCHours(); let utcMinutes = date.getUTCMinutes(); let utcSeconds = date.getUTCSeconds(); let utcFormattedDate = `${utcYear}-${utcMonth}-${utcDate} ${utcHours}:${utcMinutes}:${utcSeconds}`; console.log(utcFormattedDate);

Example

For the date 2023-03-14T12:00:00.000Z, manual calculation returns:

shell
2023-3-14 12:0:0

These methods provide flexible ways to handle UTC date conversion. You can choose the method based on your specific needs and context.

2024年6月29日 12:07 回复

你的答案