Home > Blockchain >  Correct way of converting string to date when a string is in given format?
Correct way of converting string to date when a string is in given format?

Time:10-13

I have a string with below date format

const strDate = '10-23-2022';

to convert this to date I was using below line of code

new Date(strDate);

this is all working fine in Chrome but the issue is in mozilla firefox I am getting invalid date error. So what is the correct way of converting string to date that works across all browsers?

CodePudding user response:

You can try one of them

  1. Pipe
getFormatedDate(date: Date, format: string) {
    const datePipe = new DatePipe('en-US'); // culture of your date
    return datePipe.transform(date, format);
}
  1. moment.js
    let parsedDate = moment(dateStr,"MM-DD-YYYY");
    let outputDate = parsedDate.format("DD-MM-YYYY");
  1. Simple Split
const str = '10-23-2022';

const [month, day, year] = str.split('-');

console.log(month); //            
  • Related