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
Release: 2024-12-09 10:19:07
Original
839 people have browsed it

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
Copy after login

This range needs to be converted to UTC:

2009-1-1T8:00:00 to 2009-1-4T7:59:59
Copy after login

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));
Copy after login

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
Copy after login
Copy after login

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

console.log(date.toISOString());
Copy after login

This would log the UTC date as:

2023-05-11T15:30:00.000Z
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template