What is the best way to retrieve the UTC value of a specific date and time within a particular time zone using JavaScript?

I want to create a Date object with a specific time: "Midnight in Los Angeles on Christmas 2011".

Although I've used moment.js, which is good, and moment-timezone, which is even better, neither the default Date class nor moment constructors allow for specifying a timezone as an argument.

To workaround this limitation, I have been using a formatted RFC2822 string like:

d = new Date("12-25-2011 PST")

However, this method assumes that December 25 is in standard time. When trying PDT instead of PST, the result varies:

d = new Date("12-25-2011 PDT")

My preference would be to utilize geographical-style timezones such as "America/Los_Angeles".

Answer №1

For more information on moment-timezone, check out #11 and #25.

If you want to access the most recent version from GitHub sources, you can use this code snippet:

moment.tz('2011-12-25T00:00:00','America/Los_Angeles').utc().format()

The release of the latest version is pending as we are currently deliberating on how to handle ambiguous or invalid inputs, as mentioned in #27.

Answer №2

Alright, I believe I have a solution for this task. Utilizing the fantastic timezone library from npm. Here is a brief outline of the process:

var tz = require("timezone");

var convertDateToZone = function(date, zone) {
    return new Date(tz(date, zone, require("timezone/"+zone), "%FT%T%^z"));
};

console.log(convertDateToZone([2011, 12, 25], "America/Los_Angeles"));

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 methods can be used to prevent accessing 'res' after the resolution of getServerSideProps?

While working on my nextJS application, I encountered an error in the page file: warn - You should not access 'res' after getServerSideProps resolves. Read more: https://nextjs.org/docs/messages/gssp-no-mutating-res I tried reading the provided ...

Using HTML and CSS to stack a DIV on top of another using z-index

I have 3 main layers on my website: 1) The main view with elements inside (#views in jsbin) - BOTTOM LAYER 2) An overlay (with a white background opacity of .8 #overlay in jsbin) - MIDDLE LAYER 3) A context menu (#contextmenu in jsbin) - TOP LAYER Wh ...

Real-time Updating of ChartJS Charts in Rails Using AJAX

I am currently working with Rails 5 and the latest version of ChartJS library (). My goal is to retrieve the most recent 20 items from the SensorReading model and update the Chart using setInterval and AJAX. I have successfully created the AJAX call and ...

Learn how to create a half and half color scheme in an HTML table

I have created an HTML table that resembles a calendar. Various events are registered in the calendar, each distinguished by its color. However, I am looking to change the colors of the cells to be half and half. The image I desire is similar to this: C ...

Having Trouble Showing Loading Component on Next.js v13

Having some issues with setting up a loading component in my Next.js v13 project. I followed the documentation by creating a file called loading.tsx in the src directory, but it's not appearing on the page as expected. I've also included a functi ...

Activate the next tab by clicking a button in ReactJS

I currently have a web page with 4 tabs, each containing different sets of data. Within the first tab, I have a button that should activate the next tab's content when clicked by the user. render(){ return ( <MuiThemeProvider> ...

Is it better to process data in a React app using Express or handle it directly on the front end with React?

Hey there, I need some advice on how to create a league table for my application. The JSON data structure is set up like this: I'm considering whether to calculate each player's league data on the front-end using React by looping through the fixt ...

Extracting information from an ENORMOUS Array

Let's start with my code snippet, featuring an array: var UserProfiles = [{ userProfileID: 1, firstName: 'Austin', lastName: 'Hunter', email: 'test', token: '', platform: 'android ...

No spaces are being retrieved from the input field

After entering "test data" in the first input box and clicking the submit button, only "test" is displayed in another input box. The goal is to have "test data" appear in the script-generated input box as well. Sample HTML Code <input name="" type="te ...

Trying to call an applet method using JavaScript will not be successful

When trying to invoke methods of a Java applet using JavaScript, I encounter an issue that requires the site to be added to trusted sites and security set to low in order for it to work properly. Otherwise, an error is thrown: Microsoft JScript runtime ...

Is there a way to monitor real-time updates without relying on setInterval or timeout functions?

Currently in the process of building a social network, I am working on fetching live notifications. The current approach involves sending an AJAX request every few seconds using setInterval. The code snippet for this operation is as follows: setInterval ( ...

What is the method for accessing the req, res objects within the callback functions?

One of my preferences is to access the req, res, next objects outside of the middleware function. For instance, in a sample middleware file called sample.js: var app = express(); .... ..... .... var updateUserInput = { init:function(){ get_data ...

Local email.js functionality successful, but fails upon deployment alongside React

I have implemented Email.js to create a contact form for a Next.js website. It functions perfectly when tested locally, but encounters issues once deployed. Upon clicking the submit button, the form fails to reset as intended within the sendEmail function. ...

Unexpected outcomes in linq.js

Hey there, I have a JSON object named "Faults" that looks like this: "Faults":[{"RoomId":1,"ElementId":173,"FaultTypeId":1,"Count":1,"Remark":""},{"RoomId":3,"ElementId":211,"FaultTypeId":7,"Count":1,"Remark":""},{"RoomId":4,"ElementId":173,"FaultTypeId": ...

Jade not responding to AngularJS click directive function

This tutorial is inspired by the MEAN Stack demo: Mongo, Express, AngularJS, and NodeJS I am attempting to incorporate a 'delete' method into my controller in the Jade template as shown below: characters.jade script function CharactersCont ...

What is the best way to bring a module into an Angular project?

I have a project in Angular with an additional module created as an npm package. The structure of the module is as follows: --otherModule --other-module.module.ts --index.ts --package.json index.ts: export { OtherModule } from './other-module ...

The width of Material UI Grid decreases every time it is re-rendered

I'm attempting to display a list of 25 words in a 5x5 grid using the MUI Grid component. The grid is structured as a <Grid container direction="column"> with five <Grid item> elements. Each <Grid item> contains: <Grid co ...

Safely render user-generated HTML content within a React application to prevent cross-site scripting vulnerabilities

A unique situation has arisen in our React app where a user inputs a string that is displayed to other users. The challenge lies in searching for specific characters within the string and replacing them with HTML elements. For example, transforming the wor ...

What level of trust can be placed in MUI Global Class names when using JSS?

Here is my current code snippet: const formControlStyles = { root: { '&:hover .MuiFormLabel-root': { } } } Would it be considered secure to utilize the class name in theme overrides for connecting with other components? Furthe ...

What is the best way to transfer information from df ~ to my webpage?

I'm currently working on a pie chart that visualizes the disk space usage on my Linux machine. I need help figuring out how to properly parse this data onto a microservice URL. Any assistance would be greatly appreciated. Here's what I have so f ...