Praveen
Praveen

Reputation: 56501

Unable to parse the date

I'm trying to parse the date which is in the following format

dateFormat: "d-M-y" // returns 10-Oct-13

I'm using jQuery UI for formatting date.

Below is my code:

var d1 = new Date("10-Oct-13");
alert(d1);  //Invalid in FF and IE, works in chrome

enter image description here

Seems weird, here is my JSFiddle for reproducing the bug in FF and IE.

Note: I don't want to use plugin, since it is working chrome.

Please share your thoughts.

Upvotes: 1

Views: 314

Answers (3)

michalstanko
michalstanko

Reputation: 589

You can use Datepicker's parseDate() method in conjunction with the format string to parse the date:

var d1 = $.datepicker.parseDate("d-M-y", $("#lastAssimilationDate").val())
alert(d1); // alerts: Thu Oct 10 2013 00:00:00 GMT+0200

See the edited JSFiddle.

Upvotes: 3

Blazemonger
Blazemonger

Reputation: 92893

Use the built-in getDate method:

$('button').click(function(){    
    var d1 = $("#lastAssimilationDate" ).datepicker('getDate');
    console.log(d1);    
});

You can also assign an altField with an altFormat of yyyy-mm-dd if you need to send an ISO-standard date to the server.

Upvotes: 1

Anthony Grist
Anthony Grist

Reputation: 38345

From the MDN doc for Date:

dateString

String value representing a date. The string should be in a format recognized by the parse method (IETF-compliant RFC 2822 timestamps).

Essentially you're passing a string in an unsupported date format as the dateString parameter of the constructor, so the JavaScript engine is (correctly) stating that it's an invalid date. Chrome seems to be slightly more forgiving with the date formats it allows, but that's non-standard.

You can use the getDate function to obtain a Date object representing your selected date:

var d1 = $('#lastAssimilationDate').datepicker("getDate");

Upvotes: 1

Related Questions