To convert a date from one time zone to another in JavaScript, you can utilize the built-in functions and the time zone database described in the Zone.tab file. Here's a practical solution:
The convertTZ function takes two parameters:
function convertTZ(date, tzString) { return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString})); }
Example usage:
// Convert a date to GMT+7 timezone (Asia/Jakarta) const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta"); console.log(convertedDate); // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time)
The convertedDate will be a regular Date object, allowing you to access its components:
const hours = convertedDate.getHours(); // 17
Additionally, you can pass a Date object as the first argument instead of a string:
const date = new Date(); const jakartaDate = convertTZ(date, "Asia/Jakarta"); // Current date-time in Jakarta
The above is the detailed content of How Can I Convert a Date to a Different Time Zone in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!