Search code examples
javascriptdate-formatting

javascript function to accept multiple date formats


Users want to use the following formats to enter dates:- mm-dd-yyyy OR yyyy-mm-dd OR m-d-yy OR m-d-yyyy OR mm/dd/yyyy OR m/d/yy. My plan is to capture whatever they enter and convert it to yyyy-mm-dd because that is the format that the date field value must be submitted. They have refused to use a calendar . I have tried the following JS function without any success. Any ideas?

    var value = ctrl.getValue();
    var date_input = new Date(value);
    var day = date_input.getDay();
    var month = date_input.getMonth() + 1;
    var year = date_input.getFullYear();
    var yyyy_MM_dd = year + "-" + month + "-" + day;
    return yyyy_MM_dd

Solution

  • Because its wrong to use var day = date_input.getDay();

    use it like this

    var day = date_input.getDate();
    

    function getDateFormat(value){
      var date_input = new Date(value);
      var day = date_input.getDate();
      var month = date_input.getMonth() + 1;
      var year = date_input.getFullYear();
      var yyyy_MM_dd = year + "-" + month + "-" + day;
      return yyyy_MM_dd;
    }
    console.log(getDateFormat("2017-12-30"));
    console.log(getDateFormat("12-30-2017"));

    .getDay is giving you days of weeks

    Also be sure to use date format accepted by Date