1

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?

1 Answer 1

3

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer, although I would advice not to use momentjs anymore. It’s EOL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.