Search code examples
javascriptmomentjsdate-fns

is there programmatic way to identify date format after reviewing few date strings?


Let's say I have a array of date strings,

const a = ["11/23/2018","10/22/1992","02/02/1993","01/01/1990",...];
const b = ["12/01/2018","12/12/1992","24/09/1993","16/01/1990",...];

is there way to identify data format of each of these arrays, like

a => MM/DD/YYYY
b => DD/MM/YYYY

in javascript. I am not looking for a solution in vanila javascript, if you can point me to a solution using momentjs or date-fns It would be fine.

thank you, in advance.


Solution

  • As stated in the comments, you can use momentjs Parse Date Format plug-in.

    This plug-in add the parseFormat method:

    That allows to create smart date inputs that let your users set a Date/Time and lets you extract the user's preferred format for future usage.

    parseFormat method accepts preferredOrder options to customize plug-in results for ambigous inputs. You can use preferredOrder and your own logic to get your desired result.

    Here an example of a function that returns the most frequent format in the array with extracted with default parseFormat behaviour:

    const a = ["11/23/2018","10/22/1992","02/02/1993","01/01/1990"];
    const b = ["12/01/2018","12/12/1992","24/09/1993","16/01/1990"];
    
    function getFormat(arr){
      return arr.map((elem) => moment.parseFormat(elem))
           // get most frequent element from here: https://stackoverflow.com/a/20762713/4131048
            .sort((a,b) =>
              arr.filter(v => v===a).length
            - arr.filter(v => v===b).length
            ).pop();
    }
    
    console.log( getFormat(a) );
    console.log( getFormat(b) );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
    <script src="https://gr2m.github.io/moment-parseformat/moment-parseformat.js"></script>