0

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?

oderfla
  • 1,695
  • 4
  • 24
  • 49
  • 2
    Have you tried using MomentJS to handle parsing and formatting dates? – Sid Barrack Dec 21 '21 at 16:21
  • 3
    "*The date above is an american-style date represented as string.*" no, it's not. American style string would be `12/31/2021`. With that said, in either case, it's not a standard string, so you get implementation-dependent behaviour. The date *might* be parsed as valid (whether or not is the date you actually meant is not a requirement), it *might* also simply fail. See [What are valid Date Time Strings in JavaScript?](https://stackoverflow.com/q/51715259) - only "2020-12-31" is a valid standard-compliant string which will be interpreted unambiguously. – VLAZ Dec 21 '21 at 16:25
  • @SidBarrack no, it's completely unrelated. The question you propose as a duplicate asks if you *already have* a date object, how to format it into a date string. Not if you have a date string how to parse it into a date object correctly, which is what this question asks. – VLAZ Dec 21 '21 at 16:27
  • Does this answer your question? [Opposite method to toLocaleDateString](https://stackoverflow.com/questions/30936472/opposite-method-to-tolocaledatestring) – Richard Dec 21 '21 at 16:45

1 Answers1

2

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);
    }