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?

4
  • 2
    Have you tried using MomentJS to handle parsing and formatting dates? Commented Dec 21, 2021 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? - only "2020-12-31" is a valid standard-compliant string which will be interpreted unambiguously. Commented Dec 21, 2021 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. Commented Dec 21, 2021 at 16:27
  • Does this answer your question? Opposite method to toLocaleDateString Commented Dec 21, 2021 at 16:45

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.