Converting Human-Entered Dates Into a Date Object

What would be the most foolproof method of converting dates (that is for a project I am working on that uses a ML text extractor) that humans enter into a Date() object.

This seems like quite a simple issue, but I can’t find a foolproof solution. This is because the formats vary so widely between people entering dates like "Feburary 20, 2021" to "1/1/20", as well as ones that use different formats like "2021/1/3".

Is there a prebuilt package that someone knows about?

EDIT: After some digging and experimenting, the only solution I found was to use moment.js (thanks to cWerning for the suggestion, as well as others who suggested other ideas) and input multiple templates like this:

moment(**date**,["YYYY/MM/DD","DD/MM/YYYY",etc... with other formats]

1 thought on “Converting Human-Entered Dates Into a Date Object”

  1. You can control HOW humans enter the data to ensure it is understood by a program. Example below 😀

    let values=id=>document.getElementById(id).value //to get each wanted value with relative ease >:D
    let elems=id=>document.getElementById(id) //to get each wanted elem with relative ease >:D
    let twoDigit=num=>{if(num>9){return(num)}return(0+''+num)} //this will help in Date.parse formatting >:D
    elems("btn").addEventListener('click',onClick) //scroll to see the onClick function >:D
    
    
    //for placing days
    for(let i=1;i<=31;i++){elems("day").innerHTML+=`<option value="${twoDigit(i)}">${i}</option>`}
    
    //for placing months
    var monthsArr=["January","February","March","April","May","June","July","August","September","October","November","December"]
    for(let i=0;i<monthsArr.length;i++){
      elems("month").innerHTML+=`<option value="${twoDigit(i+1)}">${monthsArr[i]}</option>`
    }
    
    //for placing years
    let maxYear=2050, minYear=1950 //can set these to whatever
    for(let i=minYear;i<=maxYear;i++){elems("year").innerHTML+=`<option value="${i}">${i}</option>`}
    
    //function that runs when you click "Submit Date"
    function onClick(ev){
      let date=new Date(Date.parse(`${values("year")}-${values("month")}-${values("day")}T00:00:00.000`))
      if(date){return alert(`New Date Recorded:\n${date}`)} //inside here you can also store correct dates or whatever(inside this if statement)
      alert("INVALID DATE.. hint, February 31st is NOT A REAL DATE")
    }
    <h2>Please Choose a Date :D</h2>
    <h3>Do note that INVALID dates would be rejected :0</h3>
    <select id="day"></select>
    <select id="month"></select>
    <select id="year"></select>
    <button id="btn">Submit Date</button>
    Reply

Leave a Comment