happytohelp
happytohelp

Reputation: 347

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

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?

Upvotes: 1

Views: 118

Answers (1)

Pradeep Kumar
Pradeep Kumar

Reputation: 1491

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); // 👉️ "10"
console.log(day); // 👉️ "23"
console.log(year); // 👉️ "2022"

const date = new Date(+year, +month - 1, +day);

console.log(date); 

Upvotes: 3

Related Questions