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

Transmitting information from the front-end Fetch to the back-end server

In my stack, I am using Nodejs, Express, MySQL, body-parser, and EJS. My goal is to trigger a PUT request that will update the counter by 1 when a button is pressed. The idea is to pass the ID of the clicked button to increment it by 1. app.put("/too ...

Utilizing the fs module in Node.js

Hello friends! Currently I am faced with an issue while trying to import the fs module in nodejs. Initially, I utilized require to import it like so: const fs = require('fs'); Everything was functioning smoothly until recently when it suddenly ...

Is there a way to automatically create distinct DOM ids every time?

As I delve into coding with JS and the DOM, I frequently encounter the need to create ids (or names) solely for the purpose of grouping DOM elements together (or associating them with each other)1. These ids (or names) are not referenced anywhere else in ...

Troubleshooting the Vue.js component rendering issue

I am trying to display only one object from the data on firebase using [objectNumber]. I want to show {{ligler[1].name}} in the template, but it is causing errors: Error when rendering component Uncaught TypeError: Cannot read property 'name' o ...

Issues arise when the Angular controller fails to load

I'm experiencing an issue with my Angular controller where the code inside its constructor is not running. Here's a snippet of the relevant pieces: conversationcontrollers.js: var exampleApp = angular.module('exampleApp',[]); console ...

Passing a JavaScript variable to PHP resulted in the output being displayed as "Array"

After sending a JavaScript variable with the innerHTML "Basic" to PHP via Ajax and then sending an email with that variable, I received "Array" instead of "Basic". This situation has left me puzzled. HTML: <label class="plan-name">Plan name: <b ...

Verify in JavaScript if the script is executing within a WinStore (WinJS) program

I am in the process of developing a JavaScript library that is compatible with both Windows Store (WinJS) applications and traditional HTML/JavaScript apps. The dependency I am utilizing loads dynamically and has separate SDKs for WinJS apps and standard w ...

Suggestions for improving the smoothness of the Bootstrap toggle hide/show feature

Recently completed my bootstrap toggle hide/show feature and everything seems to be functioning correctly, except for the transition between the different contents. The borders appear jagged and not smooth when activating the toggle. I suspect there may b ...

Unable to retrieve AJAX response

I've been working on a page where I'm using AJAX to fetch data based on the selection of radio buttons. The three options available are 'Unapproved', 'Approved' and 'All'. My goal is to display the corresponding user ...

Tips for enhancing the appearance of a React component

I have a redux form that doesn't look great, and I would like to style it. However, my project uses modular CSS loaders. The styling currently looks like this: import styled from 'styled-components'; const Input = styled.input` color: #4 ...

Preserving classes in JQuery after making AJAX requests

Before we proceed, it's important to note that I am unable to modify any of the existing calls, code, or functions. This means I must come up with a workaround solution. So, here's the situation: I have a form containing various fields and a dro ...

Retrieving a map using latitude and longitude coordinates saved in a database

I have a webpage with an embedded Google Map and a dropdown list of cities. The latitude and longitude values for each city are stored in a database. When a user selects a city from the dropdown list and clicks submit, I want the map to load with the corre ...

How to animate a left border shifting to the center using JavaScript

As I'm modifying my current div, I need to add a vertical line in the center of it. I've come across various solutions where a left border is added and then shifted using the left property by 50% (which effectively places it in the middle). Here ...

utilizing the .on method for dynamically inserted elements

I have a code snippet that triggers an AJAX request to another script and adds new <li> elements every time the "more" button is clicked. The code I am using is as follows: $(function(){ $('.more').on("click",function(){ var ID = $(th ...

ERROR: Unexpected issue occurred with v8::Object::SetInternalField() resulting in an internal field going out of bounds while utilizing node-cache in Node.js

I recently started working with API exports that contain a large amount of data, so I decided to utilize the node-cache in order to speed up the API response time, as it was taking more than 2 minutes to retrieve the data. Being new to this, I came across ...

What value does a variable have by default when assigned to the ko.observable() function?

I am in the process of learning KnockoutJS and I have implemented code for folder navigation in a webmail client. In the view code, there is a comparison being made to check if the reference variable $data and $root.chosenFolderId() point to the same memor ...

Unable to invoke functions in the child window

In my Vue page, I have a script that opens a child window using the code snippet below: this.presentation = window.open( this.$router.resolve({name:'presentation'}).href, 'child window', 'width=auto,height=auto' ) ...

The changes to the grid options do not reflect immediately on the UI Grid interface

I am currently working on a project using the UI Grid module in AngularJS. I want to include row filtering as an option, but since not all users require it and the filter boxes take up a lot of space, I decided to disable filtering by default and add a but ...

Is there a way to retrieve the line number of an error within a dynamically inserted <script> element?

When I dynamically create a script element and add it to the page, the errors do not give me the line numbers of the script itself, but instead provide the line number where I append the script. The following code in a .js file will result in an error mes ...

Problem with Pathjs routing

Can anyone help with this routing issue I'm having? Path.map("/(:page_1)(/:page_2)/").to(funct); The route is not matching for: /projects/index2/ It matches /anything, but not /anything/anything If you have any ideas, please share! ...