1

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.

Aliaksei Bulhak
  • 6,078
  • 8
  • 45
  • 75

4 Answers4

1

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

Aamir Afridi
  • 6,364
  • 3
  • 42
  • 42
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 = new Date(year, m.indexOf(month), day);

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

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;
  }
Dylan Watson
  • 2,283
  • 2
  • 20
  • 38
0

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());
Anoop
  • 23,044
  • 10
  • 62
  • 76