Challenges with date formatting arise for Spanish speakers when the date returns as NaN or an Invalid

I have been working on an Angular app

Objective: My aim is to allow users to input dates in Spanish format (DD/MM/YYYY) and display them as such, while converting them back to English format when saving the data to the Database.

Issue: One problem I encountered is that if a user types a number larger than 12 for the first two digits of the date, JavaScript Date throws an error saying it's NaN.

Attempted Solutions: I researched and came across the methods toLocaleDateString and toLocaleString. However, since these are used with Dates, I wasn't sure how they would work when dealing with a NaN value. I gave it a try anyway, but all I got was Invalid Date {}. I am operating in the central time zone, just in case that makes a difference.

TypeScript:

dateEnter(data) {
    let spanishDate = new Date(data).toLocaleDateString;
    let dobForDB = (this.localeId == "es") ? this.myMethod(new Date(spanishDate)) : data;
}

myMethod(date: any) {
    let year = date.getFullYear();
    let day = date.getDate();
    let month = date.getMonth() + 1;
    let dateString = (this.localeId == "es") ? day.toString() + "/" + month.toString() + "/" + year.toString().substring(0, 4) : month.toString() + "/" + day.toString() + "/" + year.toString().substring(0, 4);
    return dateString;
}

Answer №1

One possible solution is to consider utilizing Moment.js for this particular case. This library has the ability to recognize the user's locale settings, making it a useful tool in handling date formats. By using the L format specifier, you can easily manipulate dates according to the short date format of the locale.

moment("01/02/2019", "L").format("YYYY-MM-DD")

// Output in en-US:  "2019-01-02"  (January 2nd)
// Output in es-MX:  "2019-02-01"  (February 1st)

It's important to note that the format of dates is not solely determined by language. Various English-speaking locales may use different date formats such as DD/MM/YYYY. For example, the United Kingdom follows this format while the United States (en-US) typically uses MM/DD/YYYY. To learn more about date formats across different countries, refer to the list provided on Wikipedia's Date Format by Country page.

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 error message states: "It is not possible to destructure the property 'createComponentInstance' of 'Vue.ssrUtils' as it is undefined for nuxt and jest."

I have been working on integrating the jest testing framework into my nuxt project, but I am facing a major obstacle. I am struggling to test a simple component and haven't been able to find a solution yet. If anyone has encountered the same issue, co ...

Steps for launching a browser using Capybara and Selenium

I am completely new to utilizing Capybara and have not had any experience with Selenium in the past. Currently, I am working on a Ruby on Rails project on MacOSX and encountering an issue where the browser window does not open when I execute my test. My te ...

Exploring the power of nested loops within an AJAX call in Angular

I have been attempting to iterate through a variable, search for IDs, and then make an ajax call to retrieve the detailed content of the different IDs. In the Success function, I am trying to loop through the received content and extract the emails. While ...

Generating div elements of varying colors using a combination of Jinja templating and JavaScript loop

Utilizing jinja and javascript in my template, I am creating multiple rows of 100 boxes where the color of each box depends on the data associated with that row. For instance, if a row in my dataset looks like this: year men women 1988 60 40 The co ...

Why does jQuery only execute the very first condition or none at all if the first condition is false?

I'm trying to create a fixed button that, when clicked, scrolls to a specific section on the page. However, only the first condition seems to be working, and the other conditions are being ignored even when the first one is false. Can you help me figu ...

Leveraging a Derived-Class Object Within the Base-Class to Invoke a Base-Class Function with Derived-Class Information

I have a situation where I need to access a method from a derived class in my base generic component that returns data specific to the derived class. The first issue I encountered is that I am unable to define the method as static in the abstract class! ...

Encountering an error while attempting to load the jQuery script: TypeError - $.fn.appear.run is not a

I have included an animation script for CSS in my markup, but I am encountering the following error: TypeError: $.fn.appear.run is not a function Does anyone know why this is happening and how I can resolve it? /* * CSS3 Animate it * Copyright (c) 2 ...

Tips on using CSS to hide elements on a webpage with display:none

<div class="span9"> <span class="disabled">&lt;&lt; previous</span><span class="current numbers">1</span> <span class="numbers"><a href="/index/page:2">2</a></span> <span class="num ...

Discovering the channel editor on Discord using the channelUpdate event

While working on the creation of the event updateChannel, I noticed that in the Discord.JS Docs, there isn't clear information on how to identify who edited a channel. Is it even possible? Below is the current code snippet that I have: Using Discord. ...

Troubleshooting AngularJS POST Request Error with Request Body

I am a beginner in AngularJs and I am trying to make a post request to a server with enum form. Currently, I have the following JavaScript code: function completeTaskAction2($scope, $http, Base64) { $http.defaults.headers.common['Authorization'] ...

The Angular routing feature seems to be malfunctioning

I have encountered a frustrating issue with AngularJS routing and despite countless searches for solutions, I am still facing the same problem. In my root folder at c:\intepub\wwwroot\angular\, I have three files that I am testing under ...

Comparing JSON files in JavaScript to identify and extract only the new objects

I need a way to identify and output the newly added objects from two JSON files based on their "Id" values. It's important for me to disregard changes in object positions within the files and also ignore specific key-value changes, like Greg's ag ...

Sharing Global Variables in Node.js: What's the Best Way to Pass Them into Required Files?

Recently, I decided to organize my gulpfile.js by splitting it into multiple files within a /gulp folder. However, I encountered an issue when trying to pass a variable debug (boolean) into these files to control the behavior of the gulp command being incl ...

Retrieve selected button from loop typescript

https://i.stack.imgur.com/DS9jQ.jpgI have an array of individuals that I am looping through. It's a bit difficult for me to explain, but I want something like this: <div *ngFor="let person of persons"> {{person.name}} {{person.surname}} <but ...

Guide on activating an event when a slider image is updated using jquery

I am working on a project that includes a slider. I have been trying to trigger an event when the slider image changes, but so far using the classChange Event has not been successful. Here is the link to my code: [1] https://codepen.io/anon/pen/gzLYaO ...

Efficient access to variable-enumerated objects in TypeScript

Let's say I have the following basic interfaces in my project: interface X {}; interface Y {}; interface Data { x: X[]; y: Y[]; } And also this function: function fetchData<S extends keyof Data>(type: S): Data[S] { return data[type]; } ...

Revamp the button's visual presentation when it is in an active state

Currently, I'm facing a challenge with altering the visual appearance of a button. Specifically, I want to make it resemble an arrow protruding from it, indicating that it is the active button. The button in question is enclosed within a card componen ...

"Refine Your Grid with a Pinterest-Inspired

I've set up a grid of images in columns similar to Pinterest that I would like to filter. The images vary in height but all have the same width. The issue arises when a taller image is followed by a shorter one, causing the short image to float right ...

Change the position of an array element when displayed on an HTML page

I'm trying to figure out a way to manipulate the position of an HTML element that is stored inside an array. The issue I am facing is that my code generates a new div every time a specific function is called, and this div has a class applied to it for ...

How to use jQuery to iterate over changing elements and retrieve their data values

Exploring the potential of a collapsible panel to meet my requirements $(".sport").on("click", function() { var thisId = $(this).attr("id"); var thisChildren = $(this) + ".sportlist"; $(thisChildren).each(function(index) { }); }); <link ...