JS DateFormat Error

Discussion in 'JavaScript' started by neilfurry, Nov 23, 2017.

  1. #1
    Hi Mate,

    i have this line of code that returns an "Invalid Date" error

    //calendar textfield contains this format: 11-23-2017
    //and i want that to be on this format: 2017-11-23 to be able to return the correct date format.

    var txtdate = $("#calendar").val().split("-").reverse().join("-");
    var now = new Date(txtdate);
    alert(now);

    can you tell what im doing wrong?

    Thank you
     
    neilfurry, Nov 23, 2017 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #2
    The split is breaking them ALL up.. as such your output is 2017-23-11, which is an invalid date. Split is annoying in that if you set the limit you're going to end up with the values screwed up, so what you'll have to do is:

    
    var
      dateArray = $('#calendar').val().split('-'),
      now = new Date(dateArray[2] + '-' + dateArray[0] + '-' + dateArray[1]);
    alert(now);
    
    Code (markup):
     
    deathshadow, Nov 24, 2017 IP