What is the best way to extract the "Standard" timezone string from a given moment object?

Currently, I am tackling a project in asp.net that involves managing dates and times between a server database and client-side widgets. In order to simplify this process, I have decided to utilize moment.js.

While examining my moment object during debugging, I came across the following information:

https://i.sstatic.net/oEX0C.png

I specifically require the "Pacific Daylight Time" segment, as it is the only string format recognized by the TimeZoneInfo c# class that I am utilizing on the backend.

How can I extract this specific data?

Although I have thoroughly reviewed the documentation and guides, I have not been able to find any information pertaining to the "Standard" names of timezones. The only references available are city-based, such as "America/Los Angeles," which are not suitable for my requirements. While I could create a dictionary to map city names to standard timezone names, this approach would be time-consuming and cumbersome. Therefore, I am seeking a more efficient solution to achieve this task.

Answer №1

Utilize string parsing or leverage a C# library

I discovered two methods to extract the necessary data, however, both approaches are somewhat crude and inelegant.

  1. To extract the timezone name on the front end, one can utilize the .toString() function from the moment library and then employ pattern matching techniques to isolate the timezone name from the result.

This process involves using regex or .split() to separate the timezone name from the date string, assuming the format remains consistent. An example implementation looks like:

var timeZoneName = momentDate._d.toString().split("(")[1].split(")")[0];
//timeZoneName now stores "Pacific Daylight Time"

After transferring this value to the back end, it is necessary to replace "Daylight" with "Standard" in order to create a TimeZoneInfo instance.

  1. Alternatively, on the back end, utilize an external library to handle the mapping process.

I came across two libraries, TimeZoneNames and TimeZoneConverter, which can convert IANA-style names to their Windows Standard equivalents. The TimeZoneConverter can be used as follows:

localTZName = TZConvert.IanaToWindows(tzName);
TimeZoneInfo localTimeZone = TimeZoneInfo.FindSystemTimeZoneById(localTZName);

The tzName is obtained by using moment.tz.guess() on the front end. While this method proved effective, it essentially involves creating a mapping between the two styles, alleviating the need for manual conversion.

Although both solutions are not ideal, they serve their purpose

The first solution relies on the assumption that the moment's string representation remains consistent, prompting the need for a more streamlined method to extract this specific data without resorting to string manipulation.

The second solution involves a direct mapping approach, which may not be aesthetically pleasing but does the job effectively. Ideally, this functionality should be integrated seamlessly into either moment.tz.js or TimeZoneInfo.

The discrepancy arises from moment.js disregarding Windows compatibility, while Windows overlooks the intricate nature of timezones and their historical implications on accurate date representation.

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

The issue with AsyncPostBackTrigger persists within my application

I've encountered an interesting issue with our website setup. We're using a masterpage and I'm trying to create an update panel on one of the pages to display the group SSID upon completion. Here's the code snippet I've inserted i ...

before sending the url with fetch(url), it is adjusted

My front end code is currently fetching a URL from a local node.js server using the following snippet: fetch('http://localhost:3000/search/house') .then(.... Upon checking what is being sent to the server (via the network tab in Firefox dev ...

Troubleshooting: Unable to load template file content in AngularJS ng-view

Setting up a demo angular app has been quite the challenge for me. Despite my efforts, the content from my partial file (partials/test.html) is not loading into the layout file as expected. Below is a snippet of my index.html: <!DOCTYPE html> <ht ...

Updating numerous records with varying values

Utilizing jQuery UI's sortable feature (source) allows me to rearrange elements effortlessly. By implementing custom callbacks, I can generate a list of these elements, assigning each a new position ID as I move them around. The resulting list may app ...

Can a function be activated in JavaScript when location permission is declined?

Background: Following up on a previous question regarding the use of getCurrentPosition and async functions. I am currently working on The Odin Project and attempting to create a basic weather application. My goal is to include a feature that automatically ...

The occurrence of an unhandled promise rejection is triggered by the return statement within the fs

In my code, I have a simple fs.readFile function that reads data from a JSON file, retrieves one of its properties (an array), and then checks if that array contains every single element from an array generated by the user. Here is the snippet of code: co ...

I would appreciate it if someone could clarify how the rendering process occurs in React in this specific scenario

let visitor = 0; function Mug({name}) { visitor = visitor + 1; console.log(name, visitor); return <h2>Coffee mug for visitor #{visitor}</h2>; } return ( <> <Mug name={"A"}/> <Mug name={"B&qu ...

jQuery does not trigger the error event for a 403 status code when loading a new image src

Currently working on a project that involves implementing a static Google map on a webpage. The challenge I am facing is resizing the map dynamically when the page size changes. In order to achieve this, I have created a function that triggers on page resi ...

Adjust the anchor tag content when a div is clicked

I have a list where each item is assigned a unique ID. I have written the HTML structure for a single item as follows: The structure looks like this: <div id='33496'> <div class='event_content'>..... <div>. ...

What is the best way to calculate the difference between two dates in MongoDB?

I have two key dates: the sales_date (date of service sale) and the cancellation_date (date of service cancellation). I am looking to calculate tenure by month by subtracting the cancellation_date from the sales_date. Currently, this is the code I have: ...

Bringing in d3js into Angular 2

Is there a way to successfully import d3js into an Angular2 project? I have already installed d3js using npm and added it to my systemJs, but am encountering a traceur.js error. I also attempted to just use the latest cdn in a script tag and tried import * ...

Converting sections of JSON data into boolean values

Is there a way to convert certain parts of a JSON string into booleans? Here is an example of my JSON string: { "file_id": { "width": "560", "height": "270", "esc_button": "1", "overlay_close": "1", "overl ...

Secure your data with public key encryption and decryption using the Crypto Module in NodeJS

I have a challenge with encrypting/decrypting data using a public key that is stored in a file. The code snippet below illustrates my approach: encryptWithKey (toEncrypt, publicKeyPath) { var publicKey = fs.readFileSync(publicKeyPath, "utf8"); ...

Making an asynchronous request from jQuery to a Slim Framework API endpoint

I'm currently working on incorporating Slim into my project and I'm facing some challenges with setting up the AJAX call correctly: $.ajax({ url: "/api/addresses/", type: 'POST', contentType: 'application/j ...

Issues with zDepth functionality in Material-UI (React.js) not being functional

Can anyone explain the concept of zDepth to me? I have a component with the following render method: render() { return ( <div> <AppBar zDepth={2} title="Some title" iconElementLeft={<IconButton onClick={this ...

Instructions for transforming rows into columns in JSON format

Looking to convert an array of JSON objects into a format where rows become columns and the values at the side become column values, similar to the crosstab function in PostgreSQL. The JSON data looks something like this: {"marketcode":"01","size":"8,5", ...

Using JQuery to trigger the onchange event for a select tag

I am working with jQuery where I need to append select tags inside a table for each row. I want to add an onChange event for each dropdown on every row. However, the approach I have taken doesn't seem to be working. This is what my jQuery code looks l ...

Concentrate on elements that are activated without the need for clicking

Is it possible to trigger an action when an input is focused without the focus event being initiated by a click? $('#input').focus(function(){ if(not triggered by click) { alert('Hello!'); } }); ...

Should I avoid declaring global app variables in Angular?

After browsing several examples online, I have come across a common pattern in AngularJS code. The basic structure involves creating a new module using the angular.module() method and then retrieving it in other files within the same module. var app = ang ...

Merging HTML Array with jQuery

I am working with input fields of type text in the following code snippet: <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > ...