Utilize moment.js to format a datetime and display the corresponding timezone

I'm having trouble displaying timezones correctly using moment.js.

I attempted to use the following code:

var result = moment(someDate).format("MM/DD/YYYY HH:mm A Z");

This returns something like: 08/05/2015 06:18 PM +02:00, which is okay, but I would prefer my output to be more like 08/05/2015 06:18 PM WEDT or similar, including timezone abbreviations.

I tried using this code, but it doesn't seem to show the timezone properly:

var result = moment(someDate).format("MM/DD/YYYY HH:mm A z"); 

or

var result = moment(someDate).format("MM/DD/YYYY HH:mm A zz");

UPDATE

Following @Matt Johnson's advice, I utilized this method to display the timezone using moment-timezone-with-data.js and tzdetect.js:

var tzName = tzdetect.matches()[0];
var result = moment.tz(myDate, tzName).format("MM/DD/YYYY h:mm A zz");

Answer №1

Explained in the official documentation:

Note: starting from version 1.6.0, the z/zz format tokens are no longer supported. Find out more here.

The main issue lies in the fact that time zone abbreviations cannot be consistently retrieved directly from the browser. To access this data, an external source is required.

To solve this problem, consider utilizing the moment-timezone plugin. It offers detailed time zone information, including abbreviations. You will need to specify the exact time zone you are dealing with. For instance:

moment.tz("2015-08-05T00:00:00+01:00", "Europe/London").format("MM/DD/YYYY hh:mm A z");
// "08/05/2015 12:00 AM BST"

It's important not to mix HH (24-hour clock) with A (am/pm indicator). Stick to either using hh with A, or HH without A.

Answer №2

If you need to convert a UTC datetime to the user's current timezone, one solution is to utilize moment-timezone instead of the regular moment library. This approach works well when all of your dates are stored in UTC format within a database. Handling different timezones should not pose any problems either.

const userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const getFormattedDateTimeWithTZ = (date) => {
      return moment((date)).tz(userTimeZone).format('ddd, MMM DD YYYY, h:mm A zz');
}
// Example output: Tue, Mar 08 2022, 4:00 PM PKT
getFormattedDateTimeWithTZ('2022-03-08T03:00:00.000-08:00');

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 distribute my rabbitMQ code among different components?

I am looking for a way to optimize my rabbitMQ connection code by creating it once and using it across multiple components. Currently, every time I need to pass data to my exchange and queue, I end up opening and closing the connection and channel multiple ...

Send a request for a multidimensional array to a PHP file using AJAX

I am in need of an array containing subarrays. Within my ProcessWire page, there are pages and subpages with various fields. I have organized this information into an array of arrays as shown below. <?php $allarticles = $pages->find("template=a ...

Combining NodeJS and ExpressJS to deliver a unified JavaScript file when in production mode

Currently, I am managing multiple individual JS files in the following way: <script defer src="/js/libs/jquery.min.js"></script> <script defer src="/js/libs/plugins.js"></script> <!-- application core --> <script defer sr ...

Drop-down functionality in Bootstrap Form becomes unresponsive after screen width is decreased

I recently encountered a strange issue with my simple Bootstrap form. When I resize my browser width to mobile size or view it on a mobile device, the form stops functioning properly. Unfortunately, I am unable to provide any specific code examples at this ...

Encountering Problem with Jmeter Script Playback - Kindly Activate JavaScript to Access Page Information

I'm currently experiencing a challenge when trying to simulate the following scenario in my JMeter script. I would truly appreciate any assistance or solutions you can offer. My goal is to create a JMeter script for a form submission process within a ...

How can I retrieve the OptionID value upon click?

How can I retrieve the value of OptionID when the Add button (.plus-link) is clicked? Each list item may contain a dropdown select menu or not. <ul> <li> <div class="menux"> <div class="text-block"> ...

Using a pool.query with async/await in a for-of loop for PostgreSQL

While browsing another online forum thread, I came across a discussion on using async/await with loops. I attempted to implement something similar in my code but am facing difficulties in identifying the error. The array stored in the groups variable is f ...

streaming an HTML5 video directly from memory source

After retrieving multiple encrypted data using ajax queries and performing necessary manipulations to turn them into a valid video, I find myself at a standstill. The binary of the video is now stored in memory, but I am unsure how to display it. To confi ...

Can CSS be used to communicate to JavaScript which media queries are currently in effect?

Is there a way for Javascript to detect when a specific CSS media query is active without repeating the conditions of the media query in Javascript? Perhaps something similar to an HTML data attribute, but for CSS. For example: CSS @media (min-width: 94 ...

Error message: An uncaught promise was encountered, despite adding a catch function. I am unable to identify the issue causing this error

Why is the added catch block not functioning properly? function maxRequest(url = ``, times = 3) { // closure function autoRetry (url, times) { console.log('times = ', times); times--; return new Promise((resolve, reject) => ...

Ant Design radio group buttons are currently dysfunctional

I'm having some trouble with radio group buttons. Can anyone assist me with this issue? (your help is greatly appreciated) Current Problem: Radio Group buttons are unclickable. Not sure where the issue lies! Technologies Used: React hooks, styled-co ...

jQuery DataTables covering a CSS-anchored menu bar

My webpage has a pinned navigation menu bar at the top and some tables with interactive features using jQuery's DataTables. However, after implementing jQuery, I encountered an issue where the tables cover the menu when scrolling down, making it uncli ...

The requestify Node module encounters issues when the body contains special characters

My current project involves the use of node.js and a library called requestify. Here is the snippet of code causing some trouble: console.log('body'); console.log(body); return new Promise(function (f, r) { requestify.request(myurl, { ...

I have been unable to find a solution for the non-functioning jQuery (3.4.1 / 3.3.1) load() issue

I have been working with jQuery's .load() function Take a look at my code snippet: <html> <head> <meta charset="utf-8"> <title>load demo</title> <script src="https://code.jquery.com/jquery-3.4.1.js"> ...

Challenges with loading times in extensive AngularJS applications

We are currently tackling performance issues related to the loading time of our AngularJS application. The page takes a significant amount of time to load, and we are exploring potential causes for this delay. One factor that could be contributing to the ...

Leverage JavaScript E4X to cleverly rename specific XML elements

Currently, I am using JavaScript to manipulate XML without involving the DOM in a browser context. I need assistance with creating an E4X expression that can rename a list of tags based on a given substring. The challenge is that I may not know the exact t ...

javascript creating a module to extend a nested object

Currently, I am working on a JavaScript module that includes an object of default options. Here is a snippet of the code: var myModule = function() { // Define option defaults var defaults = { foo: 'bar', fooObject: { option1 ...

Please proceed by submitting all radio buttons that have been checked

Seeking assistance with creating a quiz application using the MEAN stack. Once all questions are attempted, there will be a submit button for checking all selected radio buttons - option 1 corresponds to 1, option 2 to 2, and so on. The current structure o ...

Comparing ngrx and redux for managing state in stateless components

Exploring ngrx/angular 8 for the first time, I'm curious to know if the angular approach of using an observable to bind a state value to the this context still allows a component to remain presentational and stateless. In the realm of angular/ngrx, c ...

Switch out the keyup event action for a click event action

http://jsfiddle.net/2q8Gn/23/ I am looking to modify the provided fiddle so that instead of having computedPageLinks update with each key press in the search input, it updates only when a button is clicked and does not change when the search input loses f ...