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
Mary-Kate OlsenOriginal
2024-12-08 08:58:13666browse

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

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

  1. Create a new Date object:
var date = new Date();
  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());
  1. Convert the UTC date to a string in ISO 8601 format:
console.log(date.toISOString());

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

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!

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