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

Customize the format of data labels in horizontal bar charts in NGX Charts

I am currently using ngx-charts, specifically the bar-horizontal module. My goal is to format the data labels and add a percentage symbol at the end. I attempted to use the [xAxisTickFormatting] property, but it seems that my values are located within the ...

Error: Unhandled promise rejection: Trying to access a property of null (specifically 'branch') causing a TypeError

While developing a dashboard for an Angular application, I encountered an error when trying to access the dashboard: ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of null (reading 'branch') TypeError: Cannot read propert ...

How can I translate these JQuery functions into vanilla JavaScript?

I am currently in the process of building a configurator using transparent images. The image configurator functions through a basic JQuery function: I have assigned each input element a data attribute called data-Image. This function identifies the data-Im ...

What is the correct way to utilize Global Variables in programming?

Having trouble incrementing the current page in my pagination script to call the next page via AJAX... In my TypeScript file, I declare a global variable like this; declare var getCurrentPage: number; Later in the same file, I set the value for getCurren ...

Angular sends a POST request using $http to open in a new tab

In my Angular application, I am trying to send a POST request to a URL ./makeFile.php. This request will create a file with contents retrieved from a database query based on the data provided in the POST. When using PHP, the browser automatically opens a ...

The Jquery ajax request fails to function properly once the webpage has been published live

We've implemented a basic jQuery ajax call. A "more" button triggers a call to another PHP file when clicked. While it worked fine on my local server and initially on the live server, it suddenly stopped working live. The code functions perfectly o ...

Switch Between Different Background Colors for Table Rows With Each Click

This script changes colors when a row in a specific column is clicked: $(document).ready(function(){ $("#rowClick").children("tbody").children("tr").children("td").click(function(){ $(this.parentNode).toggleClass("enroute"); }); }); CSS: .placed{ b ...

How can I duplicate an element twice in AngularJS, without having them appear right after each other?

Within my AngularJS template html file, I am faced with a dilemma regarding an html element: <div>This is a complex element that I want to avoid typing multiple times</div> My challenge is that I need this element to show up twice on my websi ...

InvalidSyntaxError: Client login cannot be completed due to an unexpected end of input. Please

I encountered an issue while trying to create a bot that sends welcome messages for my friend's server. Despite numerous attempts to troubleshoot the problem within my code, I have been unable to resolve it. Any assistance in solving this error would ...

Leveraging React Native to retrieve information from a promise in JSON format

After successfully fetching the JSON data, I now have an array. My question is how can I utilize the elements within this array in a React Native environment? Below is my current approach: export default function display() { const fetching = async() => ...

Is it possible to pass a random variable into an included template in Jade?

In my jade template called 'main page', I have a reusable template named 'product template'. The 'product template' is designed to display dynamic data and needs to be flexible enough to be used in multiple pages without being ...

Authentication for file uploads in Angular 2 using Dropzone and passportjs

I am currently working on implementing authentication for an admin user using Express, Passport, and MySQL in a specific page. The authentication process works fine, but I am facing an issue with verifying whether the user is logged in while uploading file ...

Issue with firing the React-Redux action has been encountered

I am currently utilizing React along with react-redux, redux and redux-actions. Within my application, I have a specific action that is responsible for verifying the validity of the token stored in localStorage to ensure it is not expired. This action loo ...

What is the best way to adjust a wide HTML table to make it narrow enough to fit perfectly within the screen width?

I need assistance with formatting an HTML table that contains multiple columns: <table id="req_header" border="2" style="overflow: auto;"> <tr> <th><i class="fa fa-solid fa-check"> ...

The variable req.body.username is not defined in the context of JavaScript

I am completely new to JS, Angular.js and node.js. I am currently working on a login-register project but facing a minor issue. Below is my code: login.ctrl.js: var app = angular.module('login-register', []); app.factory('UserLog', ...

Establish an enumeration using universally recognized identifiers

I have a JavaScript function that requires a numerical input, as well as some predefined constants at the top level: var FOO = 1; var BAR = 2; The function should only be called using one of these constants. To ensure type safety in TypeScript, I am att ...

Is there a way for me to indicate to my custom component the specific location within an input message where a value should be displayed

I'm currently developing a value selector component in ionic/angular and I've encountered an issue with the message/title that I want to pass to the component. I want to be able to specify where the selected value should appear within the message ...

How can I add content using HTML or JavaScript?

How can I append a .txt file using HTML or Java without ActiveX prompts getting in the way? It's becoming quite annoying! Is there a simple way to script this task without having to deal with ActiveX? The current script snippet looks something like ...

Having trouble getting CSS animations to work in Safari when triggered by JavaScript

By utilizing a basic CSS animation, I've managed to create a fade-in effect that relies on opacity. To kickstart the animation, I use JavaScript to ensure it waits until the browser finishes loading. While this method works seamlessly on Firefox and C ...

Discover the ways in which an AngularJS function is able to generate HTML code containing an AngularJS

There is an issue here helper.getDataForTriggeredUploadOfMFFile = function (isTriggeredUploadMF) { if (!isTriggeredUploadMF) { return 'None'; } else { return '<spa ng-click=\"previewDataOnSmartAnalytics()>Preview Data</span&g ...