skip to Main Content

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


  1. 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.

    function DeutschDate(input: string): Date | null {
      const deutschRegex = /^(d{2}).(d{2}).(d{4}),s(d{2}):(d{2})$/;
      const danskRegex = /^(d{2}).(d{2}).(d{4})s(d{2}):(d{2})$/;
    
      const deutschMatch = input.match(deutschRegex);
      const danskMatch = input.match(danskRegex);
    
      if (deutschMatch) {
        const [, day, month, year, hours, minutes] = deutschMatch.map(Number);
        return new Date(year, month - 1, day, hours, minutes);
      } else if (danskMatch) {
        const [, day, month, year, hours, minutes] = danskMatch.map(Number);
        return new Date(year, month - 1, day, hours, minutes);
      }
    
      return null;
    }
    

    Then do this :

    const date1 = DeutschDate(stringDeutschdate1);
    const date2 = DeutschDate(stringDeutschdate2);
    

    Do let me know how it goes. THanks

    Login or Signup to reply.
  2. 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:

    function parseDeutsch(s) {
      let [day, month, year, hour, min] = s.match(/d+/g) || [];
      return new Date(year, month - 1, day, hour, min);
    }
    
    ["22.02.2022, 15:56", //Deutsch
     "22.02.2022 15:56"   //Dansk
    ].forEach(s => console.log(s + ' => ' + parseDeutsch(s).toLocaleString()));

    Of course you should validate the values and check that the result is a valid date, then deal with it if it isn’t.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search