A guide to changing the time zone of a datetime string

I have a specific string that reads "2024-09-19 14:20:45" in a designated time zone, which is "America/Los_Angeles." How would I go about converting this to a datetime string in a different time zone labeled as "timezone2," such as "America/New_York" (which is three hours ahead of Los Angeles) using JavaScript?

In JavaScript, how can I achieve the equivalent of "2024-09-19 17:20:45" for "America/New_York" in the scenario mentioned above?

Answer №1

Let's give Luxon a shot for better timezone handling in JavaScript

const convertTimeZone = (inputDateStr, fromTimeZone, toTimeZone) => {
  const { DateTime } = luxon; // Using Luxon from the global object

  // Parsing the date in the original time zone
  const dateInFromZone = DateTime.fromFormat(inputDateStr, 'yyyy-MM-dd HH:mm:ss', {
    zone: fromTimeZone
  });

  // Converting to the desired time zone
  const dateInTargetZone = dateInFromZone.setZone(toTimeZone);

  // Returning the formatted date in the target time zone
  return dateInTargetZone.toFormat('yyyy-MM-dd HH:mm:ss');
};

const inputDateStr = "2024-09-19 14:20:45";
const timezoneLA = "America/Los_Angeles";
const timezoneNY = "America/New_York";
const timezoneTaipei = "Asia/Taipei";


console.log('Time in NY', convertTimeZone(inputDateStr, timezoneLA, timezoneNY));


console.log('Time in Taipei', convertTimeZone(inputDateStr, timezoneLA, timezoneTaipei))
<script src="https://cdn.jsdelivr.net/npm/luxon@2/build/global/luxon.min.js"></script>

Answer №2

let inputDateStr = "2023-08-12 09:30:15";
let timezone1 = "Asia/Tokyo";
let timezone2 = "Europe/London";

// Convert the input date string to a Date object in UTC, considering it's in timezone1
let dateInTokyo = new Date(`${inputDateStr} GMT`);

// Utilize Intl.DateTimeFormat to convert the date to timezone2
let options = {
  timeZone: timezone2,
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
};

let dateFormatter = new Intl.DateTimeFormat('en-GB', options);
let parts = dateFormatter.formatToParts(dateInTokyo);

let formattedDate = `${parts[4].value}-${parts[0].value}-${parts[2].value} ${parts[6].value}:${parts[8].value}:${parts[10].value}`;

console.log(formattedDate); // Outputs "2023-08-12 05:30:15"

This method involves:

new Date(): Parsing the string and assuming it's in UTC.

Intl.DateTimeFormat: Formatting the date according to the specified time zone, Europe/London.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to display database information on my webpage according to the selected item in the combo box?

Whenever I visit my sample.php page, the only thing that appears is my combo box. However, when I start selecting a value from the combo box, that's when the data from my database, which is fetched from getyear.php, is displayed. What I want to achie ...

When pressing the next or previous button on the slider, an error message pops up saying "$curr[action] is not a

I found this interesting Js fiddle that I am currently following: http://jsfiddle.net/ryt3nu1v/10/ This is my current result: https://i.sstatic.net/VygSy.png My project involves creating a slider to display different ages from an array, such as 15, 25, ...

The use of Array.push() within an $http.get() function in AngularJs results in an array with unexpected

I'm stuck trying to debug my code, particularly because it seems to be related to a javascript issue. The problem arises when I attempt to load a local txt file using $http.get (is there another method that might work better?). The goal is to store t ...

Troubleshooting Problem with Facebook Messenger Bot Webhook

I received the following notification: Your Webhooks subscription callback URL is not currently accepting updates. We have observed that your Webhooks subscription for callback URL has been inactive for at least 16 minutes. Please ensure that your cal ...

Cookiebot's Cookie Consent Script

I've integrated ZohosalesIQ into the CookieBot Prior Consent widget on a WordPress installation. The script provided by Zoho is: <script type="text/javascript" data-cookieconsent="statistics"> var $zoho = []; var $zoho = $zoho || {}; ...

What is the best way to show the interior color of a cube in three.js?

My plan is to create a room using THREE.js starting from a basic cube. Here's what I have written so far: function loadModelcube() { console.log("Function executed successfully"); cube.traverse( function( node ) { if( node.material ) { ...

Choose the option for overseeing safaris

Hello there! I need some help with Safari. Can you please guide me on how to disable the arrows? https://i.stack.imgur.com/1gzat.png ...

What occurs when Click events are triggered on an <object> element?

I have set up a div, and inside that container, I embedded an SVG image using object (which I plan to manipulate later...). <div id="click-me"> some random Text <object data="some.svg" /> </div> Next, I added event listeners for t ...

Convert an array of JSON objects into a grid formatted time table using the

I am using Next.js 10 to create a timetable or schedule similar to the one below: bus stop time 1 time 2 time 3 {props[0].bus stop} {props[0].times[0]} {props[0].times[1]} {props[0].times[2]} ... {props[1].bus stop} {props[1].times[0]} {props[1] ...

The i18n feature in Nuxt 3 retrieves language locales from an external API

While working on my Nuxt 3 app, I encountered an issue when trying to integrate i18n. Despite conducting extensive research, I couldn't find any helpful information, hence I have a question. I am utilizing i18n with Prismic CMS. The locales array is s ...

Can you explain the differences between offsetHeight, clientHeight, and scrollHeight for me?

Have you ever wondered about the distinction between offsetHeight, clientHeight, and scrollHeight? What about offsetWidth, clientWidth, and scrollWidth? Understanding these differences is crucial for working effectively on the client side. Without this kn ...

Utilize Node.js to gather information from various websites

I want to create a program that can download data from various websites like WHO, UNICEF, Eurostat, etc. and then convert this data into JSON format. This process is known as web scraping, right? The data may be in different formats such as html, PDF, xls ...

I am seeking a way to transform this request call from JavaScript into Ajax code

My JavaScript code includes a request function, but I believe it's outdated and I'd like to convert it into an AJAX call. Can someone assist with this update? Here is the current function in my JavaScript file: function loadRest() { const ...

Retrieve JSON object based on its unique identifier from a different JSON file

I am working with 2 API resources: and it returns JSON data like this: { "id": 771, "title": "Call to Alyce Herman - Engine Assembler", "assigned_with_person_id": 317, } provides ...

easy method for creating a hyperlink that triggers a "download" pop-up box

Is there a simple and efficient way to have some of my links trigger the 'save file as' prompt (similar to right-clicking) immediately after they are clicked for the first time? ...

Reference argument passing

Below is a snippet of JavaScript code I am using: function insertIntoTable(title, text, sketchFileName, categoryId) { var db = window.openDatabase('xxx', '1.0', 'xxx database', 5*1024*1024); db.transaction( fu ...

Do we really need to use redux reducer cases?

Is it really necessary to have reducers in every case, or can actions and effects (ngrx) handle everything instead? For instance, I only have a load and load-success action in my code. I use the 'load' action just for displaying a loading spinne ...

Remove the JSON key from all array elements while preserving their child elements

I have an array of JSON objects that looks like this: var array_json = [{"my":{"id":144,"price":12500000}}, {"my":{"id":145,"price":13500000}},{"my":{"id":146,"price":13450000}}, {"my":{"id":147,"price":11500000}},{"my":{"id":148,"price":15560000}}] My g ...

Is there a way to completely remove an element from the dom once the ajax call has returned

I've been struggling to completely remove LI elements and their content, including the checkbox input, from the DOM without success. After an ajax callback, I am calling the following function, but it only removes the contents and not the element its ...

How to retrieve the value of a <td> tag with a rowspan greater than one using JQuery

I have a dynamic table that depends on the quantity of data in the abc1 column. For example, in this instance, there are 2 rows in the abc1 column with values of 18 and 23 http://jsfiddle.net/SdN4L/ <table border=1> <tr> < ...