Moment-Timezone defaults to the locale settings after the global Moment locale has been established

I am currently developing an application using Typescript that requires features from both Moment.js and moment-timezone. To localize the date and timestamps within the application, I have set moment's locale in the main app.ts file to match the language of the device.

UPDATE: For a detailed look at the sample files with additional comments, check out this gist https://gist.github.com/spstratis/fa853f9750a095d4acd0d1196a285be9

app.ts

import * as moment from 'moment/min/moment-with-locales';

let language = appUtil.getPhoneLanguage();

moment.locale(language);

// Check if the expected locale is printed
console.log("Moment Locale = " + moment.locale());

The problem arises in the utilities module when importing moment-timezone; it defaults to the 'en' locale despite setting moment's locale globally in the main app.ts file.

Below are two utility methods where I'm looking to localize relative date strings and months, even when moment-timezone defaults them to 'en'.

I attempted to use .locale(locale) on the moment methods but saw no change. Switching to import moment instead of moment-timezone worked for some methods but failed for those requiring timezone utilities.

date-util.ts

import * as moment from 'moment-timezone';

export function dateRelativeTime(value): string {
  let timezoneId = appCache.getTimezoneId();
  let localTime = _getLocalUtcDateString(value, timezoneId);
  let dateMoment = moment(localTime, "MM/DD/YYYY hh:mm:ss A");
  let formatedDate = dateMoment.tz(timezoneId).fromNow();

  return formatedDate;
};

export function localizedMonths(): ValueList {
  let m = moment("2016");
  let months = new ValueList([]);
  for (var i = 0; i < 12; i++) {
    months.push({ ValueMember: [i + 1], DisplayMember: m.month(i).format('MMMM') });
  }

  return months;
};

Answer №1

I encountered a similar issue while working with Typescript. My goal was to configure moment-timezone to utilize the Europe/Brussels timezone and set the locale to Belgian Dutch. After some troubleshooting, I managed to resolve it with the following solution:

import 'moment/locale/nl-be';
import * as momentTZ from 'moment-timezone';
momentTZ.locale("nl-be");
momentTZ.tz.setDefault("Europe/Brussels");

From now on, you can incorporate momentTZ into your project for utilizing moment functions, for example:

const exampleDate = momentTZ().format('dddd D MMMM');

Answer №2

We encountered a similar issue in the past and had to come up with a rather unconventional solution. Even though it may seem cumbersome, both the moment and moment-timezone packages need to be included in the project. Since moment-timezone relies on moment, it's unavoidable that both will be present.

The workaround involves localizing moment and then utilizing it for moment-timezone

import moment from 'moment-timezone';
import momentLocale from 'moment';

const localeLang = ‘pt’;
moment.tz.setDefault('America/Sao_Paulo');
momentLocale.locale(localeLang);
moment.localeData(localeLang);
moment.defineLocale(localeLang, momentLocale.localeData()._config);

Answer №3

The proper way to import moment is as follows:

import * as moment from 'moment';

By doing this, you will load the individual locales as needed (on Node.js) and share the same moment dependency that moment-timezone uses. This ensures that your global locale settings will carry through correctly.

Answer №4

Are you familiar with the .format('') method in JavaScript?

moment.locale();         // en
moment().format('LT');   // 6:27 PM
moment().format('LTS');  // 6:27:51 PM
moment().format('L');    // 05/31/2017
moment().format('l');    // 5/31/2017
moment().format('LL');   // May 31, 2017
moment().format('ll');   // May 31, 2017
moment().format('LLL');  // May 31, 2017 6:27 PM
moment().format('lll');  // May 31, 2017 6:27 PM
moment().format('LLLL'); // Wednesday, May 31, 2017 6:27 PM
moment().format('llll'); // Wed, May 31, 2017 6:27 PM

UPDATE: Make sure to use the moment library that includes locales: https://momentjs.com/ mentions two versions of the moment library, one with locale support ( moment-with-locales.js ) and one without ( moment.js ).

Answer №5

When dealing with multiple languages and locales, consider utilizing the Moment.js customization feature:

import moment from 'moment-timezone';
import momentLocale from 'moment';
import 'moment/locale/en-gb';
import 'moment/locale/es';
import 'moment/locale/fr';
import 'moment/locale/pt';
import 'moment/locale/pt-br';
const localeLang = 'pt-br';
momentLocale.locale(localeLang);

const tz = 'America/Bahia';
moment.tz.setDefault(tz);
moment.updateLocale(localeLang, momentLocale.localeData()._config);

Make sure to always import moment-timezone afterwards for smooth functioning:

import moment from 'moment-timezone';

Answer №6

It is important to include the required locales before using the .format function on a moment-timezone object to ensure that moment-timezone can utilize them.

import 'moment/locale/de';

Simply importing moment with timezones in this manner will not impact moment-timezone

import * as moment from 'moment/min/moment-with-locales';

Answer №7

It's strange, but I encountered the same problem out of nowhere.
It appears that there is some additional configuration needed when using moment and moment-timezone with a specific locale.

Below is the basic setup when working with just one locale.

import 'moment/locale/ja' // or any other desired locale
import moment from 'moment'
import memontTZ from 'moment-timezone'
mementTZ.defineLocale('ja', moment.localData()._config)

You can set up multiple locales by following the example provided in the link below.
Ref: https://github.com/moment/moment-timezone/issues/647#issuecomment-439600573

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

There is a potential for the object to be 'undefined' when calling the getItem method on the window's local storage

if (window?.sessionStorage?.getItem('accessToken')?.length > 0) { this.navigateToApplication(); } Encountering the following error: Object is possibly 'undefined'.ts(2532) Any suggestions on how to resolve this issue? I am attem ...

What could be causing my callback function to fail when used within a nested function?

I am currently utilizing the callback function in conjunction with Socket.io as shown below: loadData(callback) { var client = new SyncClient(this.socket, this.project); this.client = client; //From my data function client.on("connected", () => { ...

CakePHP and Legacy Ajax Script Integration

I have an old script that I want to integrate into a cakephp application. The script uses $_POST and I'm not very experienced with this, so I need some assistance with the integration. This is what the script consists of: THE JAVASCRIPT: prototype ...

Error in Redux with TypeScript: "Argument of type 'AsyncThunkAction<any, number, {}>' is not compatible with parameter of type 'AnyAction'"

So I've been working on this dispatch function: const dispatch = useAppDispatch() const handleFetch = (e: React.MouseEvent<HTMLAnchorElement>) => { const target = e.target as Element dispatch(fetchCity(parseInt(ta ...

What methods are available to extract HTML elements from .ts files?

Exploring Angular development has been quite a challenge for me. I've heard that typescript is an extension of javascript, but when it comes to manipulating HTML elements in the .ts file, I seem to be at a loss. I attempted a simple document.getEleme ...

Is there a way to receive a comprehensive report in case the deletion process encounters an error?

Currently, I am performing a delete operation with a filter based on 2 fields: const query = await Flow.deleteOne({ _id: flowId, permissions: currentUser!.id, }); After executing the delete operation, I inspect the query object to determine its su ...

The function this.someFunction does not exist

Even though I have gone through the details of the bind requirement for methods to be associated with a React ES6 class, I am still facing challenges with this specific example: class ProductList extends React.Component { constructor(props) { super( ...

Is there a way to efficiently return an array of object and nested object keys with their full paths through recursion

My grasp of JS is still in its early stages, so understanding how the stack and recursion function can be challenging for me at this point. The task at hand involves displaying an array of object keys, including the parent object name if the object is nest ...

Tips for preventing a React component from scrolling beyond the top of the page

I am looking to achieve a specific behavior with one of my react components when a user scrolls down a page. I want the component to reach the top of the page and stay there without moving any further up. Here is an Imgur link to the 'intranet' ...

Using MUI Select with Array of Objects for values - Learn how to deselect a predefined state

I have a list of objects structured like this: [ { _id: "6311c197ec3dc8c083d6b632", name: "Safety" }, ........ ]; These objects are loaded as Menu Items options for my Select component: {categoryData && c ...

Moment JS initialization and the utc() function

I am trying to comprehend the way Moment JS initializes its moment object. For instance, let's say I want to create a moment for the date and time: April 1, 2000, 3:25:00 AM with a UTC offset of +8 hours from UTC/GMT. To represent this in JavaScript ...

Over time (a few days), the setInterval function causes the react app to become unresponsive

In my React app (Next.js), I have implemented a feature that displays a QR code refreshing every 5 seconds, alongside a clock that updates every second. Additionally, I have integrated a service worker to enable Progressive Web App (PWA) functionality and ...

Angular reactive forms are experiencing a setback where the value of '[value]' is not being properly set for controls

My scenario is as follows: <input #physicalAddress1 type="text" formControlName="PhysicalAddressLine1" /> <tfg-toggle #physicalAsPostal formControlName="PhysicalAsPostal" [onText]="'Yes'" [offText ...

HTML: Organize a slightly intricate column in a table

I am facing an issue with sorting columns in an HTML table that has 2 headers row: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="styles.css"> </head> <body> <table ...

Angular.js has been activated with the chosen:open event

I've been implementing the chosen directive for AngularJS from this source and so far it's performing admirably. However, my goal is to trigger the chosen:open event in order to programmatically open the dropdown menu as outlined in the chosen do ...

Error messages encountered following the latest update to the subsequent project

Recently, I upgraded a Next project from version 12 to 14, and now I'm encountering numerous import errors when attempting to run the project locally. There are too many errors to list completely, but here are a few examples: Import trace for requeste ...

The header() function triggers automatic page redirection instead of waiting for the form to be submitted

When I created a form that automatically sends an email upon submission, my goal was to direct the user to a thank you page after the email is sent. In my search for a solution, I stumbled upon the header() function in php and attempted to use it with the ...

Attempting to modify read-only properties is prohibited in strict mode within the context of [background: url({{XXX}}) no-repeat center center

I encountered an issue in Edge, but everything works fine in Chrome. I can't figure out what's causing the problem... <div class="container-fluid project_img" style="background: url({{_project.images.web}}) no-repeat center center;"> ...

In JQuery, an empty string will be returned if it contains the dollar sign character

In the scenario presented here, the value is retrieved accurately with the exception of when it includes a $ symbol at the beginning (e.g. $25.00), in which case it consistently results in an empty string. HTML: <input type="number" class="form-contro ...

I am looking for a way to transfer data collected from an input form directly to my email address without the need to open a new window. As of now, I am utilizing angular

Is there a way to send this data to my email address? I need help implementing a method to achieve this. {Name: "John", phoneNumber: "12364597"} Name: "John" phoneNumber: "12364597" __proto__: Object ...