Home >Web Front-end >JS Tutorial >How to Convert Local Dates to UTC Using JavaScript's Date Object?

How to Convert Local Dates to UTC Using JavaScript's Date Object?

DDD
DDDOriginal
2024-12-09 10:19:07815browse

How to Convert Local Dates to UTC Using JavaScript's Date Object?

Converting Dates to UTC in JavaScript

Suppose a user enters a date range that needs to be sent to a server expecting UTC dates. How can this conversion be achieved using the JavaScript Date object?

Scenario:

Consider an example where a user in Alaska (a timezone different from UTC) enters a date range:

2009-1-1 to 2009-1-3

This range needs to be converted to UTC:

2009-1-1T8:00:00 to 2009-1-4T7:59:59

Solution Using the Date Object:

To convert localized dates to UTC, the Date object's UTC method can be used. This method returns the number of milliseconds since the Unix epoch (January 1, 1970) in UTC. Here's an example:

const date = new Date();
const now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(),
                date.getUTCDate(), date.getUTCHours(),
                date.getUTCMinutes(), date.getUTCSeconds());

console.log(new Date(now_utc));

This code creates a new Date object from the current time in UTC milliseconds and logs it. The output would be a UTC date formatted as:

2023-05-11T15:30:00.000Z

Alternatively, you can use toISOString() to convert the UTC milliseconds to an ISO 8601 formatted string:

console.log(date.toISOString());

This would log the UTC date as:

2023-05-11T15:30:00.000Z

The above is the detailed content of How to Convert Local Dates to UTC Using JavaScript's Date Object?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn