Aliaksei Bulhak
Aliaksei Bulhak

Reputation: 6208

Parsing Date with javascript in FireFox

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

example

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

Answers (4)

Dylan Watson
Dylan Watson

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

jsFiddle

Just be aware of:

  • d - day of month (no leading zero)
  • dd - day of month (two digit)
  • M - month name short
  • y - year (two digit)
  • yy - year (four digit)

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

Anoop
Anoop

Reputation: 23208

You can use following JavaScript Library for uniform date parser across browser.

It has documentation

JSFIDDLE

code:

var value = "2Apr2014";
var date =new Date(dateFormat(value));
alert(date.getTime());

Upvotes: 0

Aamir Afridi
Aamir Afridi

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

adeneo
adeneo

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

FIDDLE

Upvotes: 1

Related Questions