Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert to toLocaleString date to new Date format

I have a condition where i’m converting date format according to toLocaleString.

const localDate = proDate.toLocaleString("en-GB").replace(/,/g, "");

here proDate is a new Date(someDate) object.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Later in my code i need to convert localDate to new Date() format.

I’m trying to pass new Date(localDate) but getting as invalid date.

The localDate format is 18/03/2023 08:45:47.

Here in my code when i’m trying to convert localDate i dont have access to proDate.

Is any workaround for this.

>Solution :

You could parse it with a regular expression since you know the format.

const localDate = new Date().toLocaleString("en-GB").replace(/,/g, "");
console.log(localDate);
const [, day, month, year, hours, minutes, seconds] = localDate.match(/(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})/);
const date = new Date(year, month - 1, day, hours, minutes, seconds)
console.log(date);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading