Home >Web Front-end >JS Tutorial >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:
var date = new Date();
var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
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!