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

get a "from" date and "to" date from a string

var string = '1: Mode: SOME Date range: 01/01/2018-31/12/2018 User: HANS'

I would like to get a date from the above string, remove all the other content and return like the below:

['2018-01-01', '2018-12-31', '201801', '201812']

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

Basically, YYYY-MM-DD, YYYY-MM-DD, YYYMM, YYYYMM.

I have tried the following but couldn’t progress more:

var res = string.match(/\d{2}([\/.-])\d{2}\1\d{4}/g);

=> ['01/01/2018', '31/12/2018']

Then another function is to get the YYYYMM part.

var arr = res[0].split("-");
return arr[0]+arr[1];
=> '201801'

Is it possible to get the four elements in a single array in an efficient way?

Thanks in advance!

>Solution :

I would do it in two steps. Find the dates, then format them.

const formatDateParts = (string) => {
    const [day, month, year] = string.split('/');
    return [[year, month, day].join('-'), `${year}${day}`];
};

const [_, date1, date2] = string.match(/(\d{2}\/\d{2}\/\d{4})-(\d{2}\/\d{2}\/\d{4})/);

const [date1Format, date1Condensed] = formatDateParts(date1);
const [date2Format, date2Condensed] = formatDateParts(date2);

const result = [date1Format, date2Format, date1Condensed, date2Condensed];
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