Home >Web Front-end >JS Tutorial >How Can I Convert a Date to a Different Time Zone in JavaScript?

How Can I Convert a Date to a Different Time Zone in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-16 14:59:11605browse

How Can I Convert a Date to a Different Time Zone in JavaScript?

Convert Date to Another Time Zone in JavaScript

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:

  • date: The original date in a specific time zone (e.g., "2012/04/10 10:10:30 0000")
  • tzString: The desired time zone string (e.g., "Asia/Jakarta")
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!

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