Reputation: 6208
I have strange date format like this dMMMyyyy
(for example 2Dec2013).
I'm trying to create Date object in my javascript code:
var value = "2Apr2014";
var date = new Date(value);
alert(date.getTime());
in Google Chrome this code works fine but in FireFox it returns Null
Can anyone suggest something to solve this problem
Thanks.
Upvotes: 1
Views: 1169
Reputation: 2323
I would suggest using something like jQuery datepicker to parse your dates.
I haven't tested it but it seems you'd need something like:
var currentDate = $.datepicker.parseDate( "dMyy", "2Apr2014" );
Just be aware of:
However if for some reason you really wanted to do it yourself, then you could check out this link: http://jibbering.com/faq/#parseDate
It has some interesting examples on parsing dates.
Whilst not exactly what you want, the Extended ISO 8601 local Date format YYYY-MM-DD
example could be a good indication of where to start:
/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* @param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* @return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
Upvotes: 1
Reputation: 23208
You can use following JavaScript Library for uniform date parser across browser.
It has documentation
code:
var value = "2Apr2014";
var date =new Date(dateFormat(value));
alert(date.getTime());
Upvotes: 0
Reputation: 6411
This fiddle works in both firefox and chrome
var value = "02 Apr 2014";
var date = new Date(value);
alert(date.getTime())
Check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Upvotes: 1
Reputation: 318182
How about just parsing it into the values new Date
accepts, that way it works everywhere
var value = "02Apr2014";
var m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var month = value.replace(/\d/g,''),
parts = value.split(month),
day = parseInt(parts.shift(), 10),
year = parseInt(parts.pop(), 10);
var date = new Date(year, m.indexOf(month), day);
Upvotes: 1