I have a string variable with different date time formats and when converting to the Date type I am getting NaN. from the TypeScript, not using any npm packages how to convert it properly
My Code
Date time format: Deutsch
var stringDeutschdate = "22.02.2022, 15:56" //Deutsch
var stringDeutschdate = "22.02.2022 15:56" //Dansk
I want to convert this to string type to Date type, with the above format
Below is the code
private getUtcDate(defaultDate : Date):Date {
const now: Date = new Date(defaultDate);
const formattedDate:string | undefined = this.locale.date.format(
now,"yyyyMMddHHmm","UTC");
if(formattedDate === undefined) {
throw new Error("failed to format date");
}
const parsedDate: Date = new Date(formattedDate);
return parsedDate;
}
2
Answers
Firstly you need to define a regex. Regex means regular expression to check the value with a specific format as defined.
Create a dynamic function as you are not using any external libraries.
Then do this :
Do let me know how it goes. THanks
The built–in parser is only required to parse 3 formats specified in ECMA-262, anything else is implementation dependent.
new Date("22.02.2022, 15:56")
produces an invalid date in Safari and Firefox at least. See Why does Date.parse give incorrect results?Consider using a library where you can parse various format timestamps by providing the format, there are plenty to choose from.
If you are confident of the format, you can parse both timestamps using something like:
Of course you should validate the values and check that the result is a valid date, then deal with it if it isn’t.