oderfla
oderfla

Reputation: 1797

Is it possible to detect different type of date in javascript?

This string:

const date = "31/12/2020";

will give an "Invalid Date" if converted to date:

const asDate = new Date(date);  
console.log(asDate);

The date above is an american-style date represented as string. Is there any chance javascript can understand dates written in different styles? So basically these:

    const date2 = "31/12/2020";
    const date = "2020-12-31";

would both give the same date?

Upvotes: 0

Views: 71

Answers (1)

TheHunter Shergill
TheHunter Shergill

Reputation: 708

You can try like this, pay attention to the NOTE part.

const date = "31/12/2020";
    //const date = "2020-12-31";
   
    var year,month,day;
    if(date.indexOf("/") > -1){
    // If you date string has "/" in then it will come in this conditon 

     const ConvertDate = date.split("/");
      ConvertDate.forEach((element, index) => {

      // ***********NOTE**************

      //Here condition can fail, 
      //If you know date will be DD/MM/YYYY format the you can directly split and assign them to variables like day = ConvertDate[0], month = ConvertDate [1], year = ConvertDate[2] 

      if(element.length == 4){
        year = element;        
        } else if(element.length == 2 && element > 12){
        day = element;
        } else if(element.length == 2 && element > 0 && element < 13){
        month = element;
        }     
      });
     console.log(year +"-"+month+"-"+day);
    }else{
    // if it is normal format do anything with it.
    console.log(date);
    }

Upvotes: 1

Related Questions