scrit
scrit

Reputation: 241

could not convert String to Date format in FF using javascript code

Could not able to convert String to date format in FF but works fine in chrome.

Below is the sample code:

<input type="hidden" name="userDate" id="userDate" value="26-Aug-2014"/>
<script>
  $(document).ready(function () {              
    var selDate = document.getElementsByName('userDate')[0].value;
    alert("selDate : " + selDate); //26-Aug-2014 in FF

    var datee = new Date(document.getElementsByName('userDate')[0].value);
    alert("datee : " + datee); //Invalid date in FF
  });
</script>

Please find the working sample in http://jsfiddle.net/h4JXs/1428/ , it works in chrome.Please suggest.

Upvotes: 0

Views: 84

Answers (1)

Matthew Graves
Matthew Graves

Reputation: 3284

The problem is that your date format doesn't fit the specification used in ECMA (which is how Mozilla will always implement their javascript engine). If you are tied to this date format you can use this as a workaround:

<input type="hidden" name="userDate" id="userDate" value="26-Aug-2014"/>
<script>
  $(document).ready(function () {              
    var selDate = document.getElementsByName('userDate')[0].value;
    alert("selDate : " + selDate); //26-Aug-2014 in FF

    var datee = new Date(document.getElementsByName('userDate')[0].value.replace('-', ' ').replace('-', ', '));
    alert("datee : " + datee); //Invalid date in FF
  });
</script>

We're essentially just messing with the format to get it to match a recognized format. Notice the "replace" functions.

If you're interested in what the ECMA specification says about Dates.

Upvotes: 4

Related Questions