Transforming the timezone of a date from the Backend to the timezone selected by the user in the User

I have an API that provides dates in the format:

12/23/2023 at 03:31 a.m. CST

My goal is to convert this to a date with the user-selected timezone in the following format:

12/23/2023 at 7:31 p.m.  

The timezone part is not required for display in the UI.

const options = {
    timeZone: tzString, //user selected timezone
    day: "numeric",
    month: "numeric",
    year: "numeric",
    hour: "numeric",
    minute: "2-digit",
};

return Intl.DateTimeFormat("en-US", options).format(new Date(date));

I've attempted this but haven't been able to get it in the correct timezone.

Any assistance would be greatly appreciated. Thank you.

Answer №1

If you're looking to change the time from one timezone to another, follow these steps:

To convert a date to a different time zone:

  1. Utilize the toLocaleString() method to obtain a string representation of the date based on the specified time zone.

  2. Feed this result into the Date() constructor.

  3. The resulting Date object will have its date and time adjusted according to the selected time zone.

const date = new Date();

console.log(
  date.toLocaleString('en-US', {
    timeZone: 'America/New_York',
  }),
); 
// "7/25/2023, 11:32:29 AM"

console.log(
  date.toLocaleString('ca-CA', {
    timeZone: 'Canada/Pacific',
  }),
);
// "25/7/2023 8:32:29"

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

Sequelize throwing Javascript heap out of memory error when inserting large files into database

I have successfully converted an excel file to MySQL on my local machine. However, when I try to do the same with larger files on a container limited to 2048MB of memory, it doesn't work. I attempted to increase the memory limit using node --max-old-s ...

The arrow icon for selecting input in Material Dashboard React is missing

Source Code View Result Why is the arrow icon not visible when viewing the select like this? I am using "@mui/material": "^5.8.6". Can someone please help me with this? <Box sx={{ width: "auto" }}> <FormControl fullWidth> ...

View the selected radio buttons and checkboxes next to each other in real-time before finalizing and submitting

Within my form, individuals have the option to select from radio buttons and checkboxes. The challenge is that I need to display the chosen data on the page before they enter their email and submit! Since I cannot refresh the page, PHP won't work for ...

attempting to fulfil a promise through a resolution

I am currently attempting to use a resolve with a promise in response to an issue with filters that I am currently tackling. However, my resolve function is not yet functioning as expected. I have decided to implement this approach based on advice I recei ...

What could be causing "Unknown property" errors when using unicode property escapes?

The MDN website provides examples of matching patterns with unicode support, such as: const sentence = 'A ticket to 大阪 costs ¥2000 ...

What is the best way to insert a button at the end of the last row in the first column and also at the

I am working on a JavaScript project that involves creating a table. My goal is to dynamically add buttons after the last row of the first column and also at the top of the last column. for (var i = 0; i < responseData.length; i++) { fo ...

A guide on integrating Pug templating engine with ReactJS

For the integration of Pug with a freshly created ReactJS application, I followed these steps: 1. Started by creating a new ReactJS app using create-react-app 2. Next, I referred to the instructions on babel-plugin-transform-react-pug for installing the ...

Drawing a personalized cursor using JavaScript on a canvas

I've been working on creating a canvas that allows for drawing in vanilla JavaScript. Although I've successfully enabled drawing on the canvas, I'm now looking to implement a feature where a preview dot shows up when the user presses down be ...

Tips for preventing the loss of ajax calls when an Oauth access-token expires

As the creator of a JavaScript browser application (SPA) that communicates with a server protected by OAuth 2, I encounter the challenge of using short-lived access tokens and longer-lived refresh tokens. While this specific scenario involves my own server ...

Using Node.js to render when a task has been completed

I am currently developing a Node.js Application using Express.js. One of the challenges I face is rendering data from another site on a page using Cheerio.js. While this in itself is not an issue, I struggle with determining how to render the data once the ...

Differences Between DOM and Refs in React

When it comes to React, what distinguishes the use of DOM from Refs? While it is possible to utilize typical JavaScript DOM node selectors in React for targeting specific elements, refs also offer a way to achieve the same functionality. What are the adv ...

Can HTML/CSS be used to specifically target handheld mobile devices?

I am looking to optimize my video display in HTML by only showing it on desktop browsers. The difference in bandwidth between desktop and mobile devices is affecting the performance of mobile browsers, so I want to target only desktop users. Is there a way ...

Getting variables from different functions in Python can be achieved by using the return

I am trying to implement a feature where I can fetch a search term from the function getRandomVideo() and then use it in a jQuery statement. For example, if I get "Beethoven" as the search term from the variable searches, I want to use it to retrieve JS ...

Guide for using express.js

Similar to how you can use to view the source code of all classes in Java, is there a resource available to view the source code of the express module? ...

What is the process of importing a JSON file in JavaScript?

Is there a way to import a JSON file into my HTML form by calling $(document).ready(function (){});? The properties defined in the JSON file are crucial for the functionality of my form. Can anyone guide me on how to achieve this? ...

Error message "invalid function call this.job.execute" when using Node.js node-schedule npm package

Having just started with nodejs, I created a nodejs program and set it to run every minute using the node-schedule library. However, after running for some time and producing several logs in the console, I encountered an error stating that this.job.execute ...

Here is a way to prevent a null input value from being accepted in a JavaScript function

Hey there, I have a function that looks like this: class Fun { pem_Files_Checker_And_Adder_Server_Id_Adder(id , serverType , hostname) { //do something }; }; } In order for this function to work properly, I need to give it some values. For exam ...

Arrange pictures and div elements in a horizontal layout

I am facing an issue with my code that is displaying 5 'cards' in a messed up layout instead of a straight line. I have tried to align them vertically, but some are still higher and not in the right positions. For reference, I want the layout to ...

What could be the reason for the sudden failure of my jQuery + AJAX functionality?

As a novice in JavaScript/jQuery/AJAX, I have a suspicion that the issue lies in some typo that I may have overlooked. Everything was working perfectly, but when I made some edits, the hide() + show() methods stopped functioning (I tested it on both Firefo ...

Create a custom element in React to detect and encapsulate links

I could really use some assistance with this issue. I have a bunch of text blocks containing links and have been utilizing linkifyjs's React component to automatically wrap the links in anchor tags. However, now I am looking to add a custom button nex ...