Convert Date to Another Timezone in JavaScript
Introduction
This tutorial explains how to convert a date from one timezone to another in JavaScript using the moment-timezone
library.
Step 1: Install the Required Libraries
First, you need to install moment
and moment-timezone
libraries. If you are using Node.js, you can install them via npm:
npm install moment moment-timezone
If you are working in a browser environment, you can include these libraries directly from a CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.34/moment-timezone-with-data.min.js"></script>
Step 2: Parse the Date String
Use moment
to parse the date string. The format of the date string is "YYYY/MM/DD HH:MM:SS +ZZZZ"
, where +ZZZZ
represents the timezone offset.
const dateString = "2012/04/10 10:10:30 +0000";
const date = moment(dateString, "YYYY/MM/DD HH:mm:ss Z");
Step 3: Convert to the Target Timezone
Use the tz
method from moment-timezone
to convert the parsed date to the specified timezone. For example, to convert the date to the "Asia/Jakarta" timezone:
const timezone = "Asia/Jakarta";
const convertedDate = date.tz(timezone);
Step 4: Format the Converted Date
Format the converted date back to a string. You can use the format
method to achieve this:
const formattedDate = convertedDate.format("YYYY/MM/DD HH:mm:ss Z");
console.log(formattedDate); // Outputs the date in the "Asia/Jakarta" timezone
Full Example Code
Here’s the complete code combining all the steps:
const moment = require('moment');
const momentTimezone = require('moment-timezone');
function convertTimezone(dateString, timezone) {
// Parse the date string
const date = moment(dateString, "YYYY/MM/DD HH:mm:ss Z");
// Convert to the target timezone
const convertedDate = date.tz(timezone);
// Format the converted date
return convertedDate.format("YYYY/MM/DD HH:mm:ss Z");
}
// Example usage
const dateStr = "2012/04/10 10:10:30 +0000";
const timezone = "Asia/Jakarta";
const result = convertTimezone(dateStr, timezone);
console.log(result); // Outputs the date in the "Asia/Jakarta" timezone
Explanation of Each Step
Installing Libraries: This step ensures that you have the necessary tools (moment
and moment-timezone
) to handle date and time conversions.
Parsing the Date String: Using moment
, you convert a date string into a moment object which allows further manipulations.
Converting to the Target Timezone: The tz
method of moment-timezone
allows you to convert the parsed date to a specified timezone.
Formatting the Converted Date: Finally, the format
method is used to convert the moment object back into a human-readable string format.
Additional Resources
For more detailed information and advanced usage, refer to the following links: