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;
}