Program to match different date formats and manipulate dates

Saurabh Staff asked 1 year ago

Write a function changeDateFormat() that will accept an array of dates like [“2010/03/30”, “15/12/2016”, “11-15-2012”, “2013720”];
and returns an array of dates which match formats MM-DD-YYYY, YYYY/MM/DD or DD/MM/YYYY.
For eg:- Input : [“2010/03/30”, “15/12/2016”, “11-15-2012”, “2013720”] should return [“20100330”, “15122016”, “11152012”]
 
How to solve this ?

1 Answers
Saurabh Staff answered 1 year ago

function init() {
    var dates = [“2010/03/30”, “15/12/2016”, “11-15-2012”, “2013720”];

    console.log(changeDateFormat(dates));
}
function changeDateFormat(dates) {
    var newDates = [];
    for (var i = 0; i < dates.length; i++) {
    var delimiter = checkDates(dates[i]);
    if (delimiter) {
        newDates.push(dates[i].split(delimiter).join(”));
    }
}

    return newDates;
}

function checkDates(date) {
    var regex1 = /((0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])-[12]\d{3})/, //regexMM-DD-YYYY
    regex2 = /([12]\d{3}\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01]))/, // regexYYYY/MM/DD
    regex3 = /((0[1-9]|[12]\d|3[01])\/(0[1-9]|1[0-2])\/[12]\d{3})/ // regexDD/MM/YYYY
    if (date.match(regex1)) {
        return ‘-‘;
    }

    if (date.match(regex2) || date.match(regex3)) {
        return ‘/’;
    }
   
    return null;
}