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

In JavaScript, how do I parse a Date that is always day followed by the month followed by the year?

I’m using Moment.js to parse the Date from a string, however every time I parse it I have to specify the format the string is in, but my string can either be dd-MM-yy or d/m/yyyy or d-MM-yyyy, its always changing, so writing out all the different formats will be challenging, is there a way to parse it if I know the string will always be the day followed by the month followed by the year? Either with JavaScripts date constructor or a third party library like Moment.js

>Solution :

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

read this example code

const dateString = "05-05-2023"; // example date string in "day-month-year" format

const parts = dateString.split(/[-\/]/); // split the string into parts using either "-" or "/" as the delimiter

const year = parts[2];
const month = parseInt(parts[1]) - 1; // subtract 1 from the month because it is zero-indexed in the Date() constructor
const day = parts[0];

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

console.log(date); // Fri May 05 2023 00:00:00 GMT+0000 (Coordinated Universal Time)
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