Preserve the specific date and time in the designated timezone

Utilizing the react-datePicker library requires using new Date() as input. I need to save the user's selected date, time, and timezone in such a way that regardless of their location, they will see Feb 10 2024 02:00 BST in the Date Object.

Currently, using

new Date("2024-02-10T03:00:00.000Z")
returns
Sat Feb 10 2024 08:30:00 GMT+0530 (India Standard Time)
. My goal is to have it displayed as `Sat Feb 10 2024 08:30:00 GMT+0100 (British Summer Time).

I've already attempted:

const tzname = "Europe/London";
const longOffsetFormatter = new Intl.DateTimeFormat("en-US", {timeZone: tzname ,timeZoneName: "longOffset"});
const longOffsetString = longOffsetFormatter.format(new Date("2024-02-10T03:00:00.000")); 

Although Moment.js could solve this issue, it is considered legacy and not recommended for use. How can I store the Date according to the provided timezone rather than the local timezone?

Answer №1

To enhance your time handling capabilities, consider leveraging the power of luxon, a library that offers modern alternatives to Moment.js and includes comprehensive timezone support.

const { DateTime } = require('luxon');

// User-provided inputs
const selectedDate = '2024-02-10'; // Sample date
const selectedTime = '02:00'; // Sample time

// Merge date and time into a unified string
const dateTimeString = `${selectedDate}T${selectedTime}:00.000`;

// Generate a DateTime object based on the user's selections in UTC
const utcDateTime = DateTime.fromISO(dateTimeString);

// Convert the UTC DateTime object to the local time zone
const localDateTime = utcDateTime.setZone('local');

// Format the local DateTime object as desired
const output = localDateTime.toLocaleString({
  weekday: 'short',
  month: 'long',
  day: 'numeric',
  year: 'numeric',
  hour: 'numeric',
  minute: '2-digit',
});

console.log(output); 

The resulting output is

Sat, February 10, 2024, 2:00 AM // Alternatively
Feb 10 2024 02:00 BST

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

Modifying routes within the beforeEach function causes issues when the callback incorrectly passes in erroneous routes to and from

I'm currently in the process of developing a mobile frontend using Vue. My goal is to have route transitions dynamically change to slide either left or right based on the current tab index. To accomplish this, I've set up a transition component ...

Capturing errors during function declaration in JavaScript

A problem has arisen in the below function definition due to a script error function foo () { try { var bar = function() { ERROR } } catch (exception) { console.debug("exception"); } } foo(); However, th ...

Creating a function for loading dynamic content in XSLT can be achieved by following these steps

When I call the function collapseandexpand() for static elements only, it does not work. Now, how can I create the same function to handle dynamic content in xslt? Javascript Code: <script language="javascript" type="text/javascript> <xsl:text&g ...

Formik Alert: Update depth limit reached

Currently, I am working on an EDIT formik form that is displayed as a MODAL. The issue arises when the setState function is triggered with setState(true), causing the form to appear without any onClick event. Despite changing onClick={editStory} to onClick ...

I'm looking to find the Angular version of "event.target.value" - can you help me out?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/pages/home/home.component.html I am currently working on getting the dropdown menu to function properly for filtering the flags displayed below it. My initial thought was to replicate the search ...

Display a hidden division when a radio button is selected using Javascript and Jquery

Currently, I am in the process of constructing a form that triggers a series of additional questions based on the selected answer. Below is my current working code snippet: $(".appliedWorked").click(function(){ if($(this).val()==="appliedWorkedYes") ...

Using AJAX to submit a form and retrieve response data in Javascript

After successfully getting everything to post correctly, I encountered a problem with this script. It keeps loading the content into a new page. Could it be related to the way my php file returns it using "echo(json_encode($return_receipt));"? <s ...

Upgrade angular-chart.js when applied to a filtered collection

I recently started working with Angular and encountered an issue while incorporating Angular Charts JS. I have a list that can be filtered using search text, and I want my charts to update whenever the list is filtered. What would be the best approach to ...

Creating an HTML string and then displaying its outer HTML in IE10 can be easily achieved. Just write the

My task is to write an HTML string to an element and then retrieve the resulting outer HTML from that element. This needs to be operational in IE10, latest versions of FF, Chrome, Safari, Android, iOS Safari but does not have to support any older browsers. ...

Unique loading animations are assigned to each individual page within the Next.js framework

Is there a way to have unique loading animations for each of my website pages during the loading process? How can I achieve this? I've attempted to put the loading component on the page component directly, but it doesn't seem to work: //Page com ...

Seeking a more deliberate option instead of using $(window).load, one that is not as quick as $(document)

Currently, my goal is to utilize JavaScript to conceal my preloader once the DOM and key elements have been loaded. The issue lies in the fact that various iframes on my page can significantly slow down this process. It seems that using jQuery's $(do ...

Exploring the dynamic world through HTML5 canvas and animated objects

Today I am exploring HTML 5 canvas and experimenting with moving 3 circles on the canvas. Based on my research, it looks like I need to continuously redraw the circles (perhaps every 60 milliseconds) and clear out the old circle before rendering the new on ...

having trouble transferring the password field in PHP to phpMyAdmin

My HTML form collects the user's first name, last name, username, and password. I am trying to upload this data to my local phpMyAdmin, but I'm facing an issue with storing the password in the database. Below is my HTML code: <input type="te ...

Utilize context.isPointInPath(x, y) in HTML5 Canvas for intricate shapes that contain multiple paths

I am currently working on a project that involves drawing a complex shape composed of 6 thin lines and two thick lines. In my code, I have defined 8 paths to achieve this: context.save(); context.lineWidth=2; var TAB_ABSTAND=10; var T ...

Transformation of visuals with alteration of status

I am attempting to change the image of a door from closed to open when the status changes in my home automation dashboard. I need help with this task. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&qu ...

What is the best way to calculate the width for each of the three elements in a row so that they all have 300px

Creating my own framework using flexbox has been an interesting journey. One of the major challenges I faced with flexbox is when dealing with an odd number of elements in a row, such as 3, 5, or 7. To tackle this issue, I decided to use JavaScript/jQuery. ...

I am facing an issue where my AngularJS code is not executing properly on JSF

I'm trying to clear the text inside a textarea using AngularJS after typing and clicking on a button. Here's the link to the fiddle for reference: http://jsfiddle.net/aman2690/2Ljrp54q/10/ However, I keep encountering the following error messag ...

enhancement in bringing in ... from

Hey there, I've been working with Vue.js and came across an interesting challenge. In order to use components in Vue.js, you usually need to import them individually. I thought of a solution where we could create a module containing paths to all the c ...

What is the best way to keep a button visible at all times and active without needing to be clicked?

<v-card :style="{ textAlign: 'left' }" class="basic-card pa-6" :class="{ 'small-padding': !$vuetify.breakpoint.xl }" elevation="0" flat :height="windowHeight - 104 + 'px&ap ...

What is the best way to implement validation for a textfield to prevent submission if a negative value is entered?

I am working with a text field of type number and I have successfully set a minimum value of 0 to ensure that negative values are not accepted. However, I have encountered an issue where I am unable to delete the 0 once it is entered. Is there a way to fix ...