Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 = newDate(year, m.indexOf(month), day);

FIDDLE

Solution 2:

This fiddle works in both firefox and chrome

var value = "02 Apr 2014";
var date = newDate(value);
alert(date.getTime())

Check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Solution 3:

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 notmatch 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.
   */
  functionparseISO8601(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);
      }
    }
    returndate;
  }

Solution 4:

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

It has documentation

JSFIDDLE

code:

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

Post a Comment for "Parsing Date With Javascript In Firefox"