Home > Web Front-end > JS Tutorial > How Do I Convert Localized Dates to UTC in JavaScript?

How Do I Convert Localized Dates to UTC in JavaScript?

Mary-Kate Olsen
Release: 2024-12-08 08:58:13
Original
671 people have browsed it

How Do I Convert Localized Dates to UTC in JavaScript?

Converting Dates to UTC in JavaScript

When working with international data, it is often necessary to convert dates to and from Coordinated Universal Time (UTC). JavaScript provides several methods to handle this conversion, including the Date object.

Converting a Localized Date Range to UTC

Consider the following date range input from a user:

2009-1-1 to 2009-1-3
Copy after login

To convert this date range to UTC, follow these steps:

  1. Create a new Date object:
var date = new Date();
Copy after login
  1. Use the UTC methods to get the UTC equivalents of the date's components:
var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(),
                date.getUTCDate(), date.getUTCHours(),
                date.getUTCMinutes(), date.getUTCSeconds());
Copy after login
  1. Convert the UTC date to a string in ISO 8601 format:
console.log(date.toISOString());
Copy after login

This will output the date range in ISO 8601 format, which is expected by the server:

2009-01-01T08:00:00.000Z to 2009-01-04T07:59:59.999Z
Copy after login

Note that JavaScript uses the "Z" suffix to indicate that the time is in UTC.

By following these steps, you can easily convert localized dates to UTC using JavaScript. This is essential for sending dates and times to servers that expect data in a different time zone.

The above is the detailed content of How Do I Convert Localized Dates to UTC in JavaScript?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template