force user to enter date time in mm/dd/yyyy hh:mm:ss am/pm format in angular

Viewed 50

I am creating directive which mask input field to enter MM-DD-YYYY HH:MM:SS AM/PM. So far i am able to mask MM/DD/YYYY but i am not able to add time mask. Please help.

transform(value) {
  if (value) {
    let text: string = value;
    if (text.match(/^\d/gi) != null) {
      // Removing all alphabets if string starting with zero
      text = text.replace(/[a-z]/gi, "");
    }

    if (text.match(/^N/gi) != null) {
      return text.replace(/^N\d$/gi, "N").replace(/(?!n|a)[a-z]/gi, "");
    }

    return text
      .replace(/^(\d{2})$/g, "$1/") // To put a '/' after MM/
      .replace(/^(\d{2}\/\d{2})$/g, "$1/") // To put a '/' after MM/DD/
      .replace(/^(\d{2}\/\d{2}\/\d{4})$/g, "$1 ") // To put a '/' after MM/DD/
      .replace(/^(\d{2}\/\d{2}\/\d{5}\/\d{2})$/g, "$1:")
    // need replace regex for hh:mm:ss am/pm Please help


  } else {
    return '';
  }

}

1 Answers

This will be much easier.

    function transform(input) {
      const date = new Date(input.replace(" ", "T"));
      return date.toLocaleString('en-GB');
    } 

    const input = "2022-12-12 12:12:12";
    console.log(transform(input));

Related