The current moment locale setting does not appear to be correctly updating the locale on

Having dates in different cultures (e.g. 19.10.2020 (German) 2020/10/19 (English)), I need to standardize the format as en-US (YYYY-MM-DD) when saving to the database. This is the approach I've taken:

// Function to convert any date locale (e.g. fr, de, ja, sv, nb) to en-US locale for database storage
reverseDateToEnLocale(date: string, format?: string) {
  var locale = moment();
  locale.locale(this.locale); // Setting the locale to fr, zh, de, en, etc.
  if (!format) { format = "YYYY-MM-DD"; } // Desired format for database storage
  var localeFormat = moment.localeData().longDateFormat('L'); // Getting the current moment locale date format
  return moment(date, localeFormat).format(format); // Convert the format to en-US
}

However, when I include the following in the code:


    var locale = moment();
    locale.locale(this.locale); 
    console.log(moment().locale()); // Always returns the en locale

I don't want to modify the global moment locale setting. I only want the function to use a specific locale for converting to the desired English date format.

This code snippet works correctly with German dates but has issues with Chinese dates. I'm unsure what might be missing.

When passing 'zh' as the locale, the moment locale is not being set, resulting in an incorrect format being returned.

I've also attempted setting the locale using the following approach from https://momentjs.com/docs/#/i18n/:

moment.locale('en'); // Default to English locale
var localLocale = moment();

localLocale.locale('fr'); // Setting this instance to use French
localLocale.format('LLLL'); // Sunday, July 15 2012 11:01
moment().format('LLLL'); // Sunday, July 15 2012 11:01 AM

Unfortunately, this approach is not resolving the issue. Can you help me identify what might be wrong?

Answer №1

After some research, I discovered that moment.js only accepts a specific set of locale keys for formatting dates and numbers. The localeId 'zh-Hant' that I was trying to use was not supported by moment.js. It's important to only use the locales listed by moment.js to avoid any issues. You can find a list of available locale keys here.

It took me a while to realize this, so I wanted to share this information to help others. Stick to the locales approved by moment.js for seamless date and number formatting without any errors.

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 process for incorporating the jsnetworkx library into an ionic or angular 4 project?

When using any Ionic3 app service import * as jsnx from 'jsnetworkx'; The output error message is: Uncaught (in promise): Error: Cannot find module "lodash/lang/isPlainObject" Error: Cannot find module "lodash/lang/isPlainObject" at webpackMis ...

Retrieving the value of a variable within an object using an Observable

Can someone help me figure out how to assign a variable to a value inside an object in an Observable in my typescript file? I can retrieve the variable's value in my HTML file, but I seem to be missing something crucial. I believe the solution may inv ...

Caution: Updating a component is not possible during the rendering of another component. ReactJS

I am encountering an error in my ReactHooks/Typescript application with a Navigation component that renders a PatientInfo component. The PatientInfo component is conditionally rendered based on the props it receives, determined by a searchbox in another ch ...

Functional interceptor causing Router.navigate() to malfunction

This is a custom Angular interceptor designed to handle potential session timeouts during the usage of an application. export const sessionExpiredInterceptor: HttpInterceptorFn = (req, next) => { const router: Router = inject(Router); return nex ...

Error: Attempting to access the 'user' property of a null value

I need help passing a unit test for my isAdmin() function. The function is supposed to return a role, but I keep getting an error that says 'user' cannot be read. I think the issue lies in how I am handling the user information provided by curren ...

Is there a point in bundling NPM packages if they are ultimately going to be bundled by the project

I'm in the process of creating a TypeScript package for publication on NPM. My plan is to utilize this package in upcoming web development endeavors, most likely utilizing Vite. As I look ahead to constructing a future website with this module, I am c ...

Is there a way to turn off the warning overlay in a React application?

I’m currently using react-app-rewired and I am trying to figure out how to turn off the overlay that displays Typescript warnings whenever I compile. It seems like some warnings that are not caught by the VSCode Typescript checker pop up on this overlay ...

Angular dynamically filling in a table with incomplete object data

I am currently working on a scientific project that involves displaying large amounts of data in tables. The experiments I'm working with have timestamps that follow this format: interface TimeData { time: string; data: {SD: string, SEM: string ...

Solving CORS issues on an emulator with Ionic3 and Angular4

I'm currently testing my Ionic 3 app on a Genymotion emulator and running into an issue with HTTP requests due to CORS. Initially, I believed it was a server problem but after checking the same server with an Ionic 2 app, everything seemed fine. Surpr ...

What is the purpose of running tsc --build without any project references?

Out of curiosity, I decided to experiment by executing tsc --build on a project without any project references. Surprisingly, the command ran smoothly and completed without any issues. I expected there to be a warning or error since the build flag is typic ...

Using typescript with create-react-app - organizing types in a separate file

I'm currently developing a project using Create React App with TypeScript (create-react-app myapp --typescript) In my App.tsx file, I have written some TypeScript code that I want to move to an external file. I have tried creating App.d.ts, index.d.t ...

Element not chosen in Angular version 6

Recently delving into Angular 6, I've been working on setting up form validation within an Angular form. Validation has been successfully implemented, but there's a minor issue with the select box displaying an empty first value. Here is my code ...

Is the ID sent upon selection change?

<select class="form-control" type="text" required (change)="onChangeLov($event)">> <option value=""></option> <option *ngFor ="let contact of contacts">{{contact.id}} - {{contact.name}}, {{contact.ptechnologyName}}, ...

Setting form values using Angular 9

I am currently facing a challenge that I could use some assistance with. My dilemma involves integrating a new payment system, and I seem to be encountering some obstacles. Here is a snippet of what I have: options: PaystackOptions= { amount: 5000, emai ...

Updating a property in React by fetching data from API and storing it in the cache

Recently, I implemented nanoid to generate unique IDs for my NBA team stat tracker app. However, upon browser refresh, the fetch function generates new IDs for each team stored in the favorites list. This causes the app to fetch data again and assign a new ...

Angular 2: Issue with Table not Being Updated

https://i.stack.imgur.com/qLDUZ.png The UsersList component opens a new page upon clicking the table. https://i.stack.imgur.com/WwqIX.png After changing and saving user values, the updated value is not immediately reflected in the grid for the first tim ...

Using Two Unique Typeface Options in Material UI for ReactJS

Currently, in my React App, I am utilizing the Material UI library with Typescript instead of regular Javascript. I've encountered a small hurdle that I can't seem to overcome. The two typefaces I want to incorporate into my app are: Circular-S ...

What is the consensus on incorporating client-side routing in conjunction with the server-side routing features offered by angular-universal

I am diving into the world of Angular Universal and exploring 'isomorphic' javascript for the first time. I am a bit puzzled about how to set up a logical routing system. Should I treat Angular Universal as a typical Node.js REST API? Or is its ...

Apply a dynamic function to assign a background color to a specific class

Currently, I have a function called getBackground(items) that returns a background color from a JSON file list. Within my application, there is a component that automatically adds a class name (.item-radio-checked) when a user clicks on an item in the list ...

Angular4's integration with AngularFireAuth for Google authentication is causing users to be redirected back to the source page before they can successfully

Previously, this feature was functioning perfectly. However, the current issue is that the browser is redirecting to a long URL and then quickly returning to the original source URL. This prevents users from logging into their Google accounts. authentica ...