Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new Date() in Javascript from a non-standard date format

Tags:

javascript

I have a date in this format: dd.mm.yyyy

When I instantiate a JavaScript date with it, it gives me a NaN

In c# I can specify a date format, to say: here you have my string, it's in this format, please make a Datetime of it.

Is this possible in JavaScript too? If not, is there an easy way?

I would prefer not to use a substring for day, substring for month etc. because my method must also be capable of german, italian, english etc. dates.

like image 226
Michel Avatar asked Sep 01 '25 18:09

Michel


2 Answers

You will need to create a function to extract the date parts and use them with the Date constructor.

Note that this constructor treats months as zero based numbers (0=Jan, 1=Feb, ..., 11=Dec).

For example:

function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // note parts[1]-1
  return new Date(parts[2], parts[1]-1, parts[0]);
}

parseDate('31.05.2010');
// Mon May 31 2010 00:00:00

Edit: For handling a variable format you could do something like this:

function parseDate(input, format) {
  format = format || 'yyyy-mm-dd'; // default format
  var parts = input.match(/(\d+)/g), 
      i = 0, fmt = {};
  // extract date-part indexes from the format
  format.replace(/(yyyy|dd|mm)/g, function(part) { fmt[part] = i++; });

  return new Date(parts[fmt['yyyy']], parts[fmt['mm']]-1, parts[fmt['dd']]);
}

parseDate('05.31.2010', 'mm.dd.yyyy');
parseDate('31.05.2010', 'dd.mm.yyyy');
parseDate('2010-05-31');

The above function accepts a format parameter, that should include the yyyy mm and dd placeholders, the separators are not really important, since only digits are captured by the RegExp.

You might also give a look to DateJS, a small library that makes date parsing painless...

like image 67
Christian C. Salvadó Avatar answered Sep 04 '25 09:09

Christian C. Salvadó


It's easy enough to split the string into an array and pass the parts directly to the Date object:

var str = "01.01.2010";
var dmy = str.split(".");

var d = new Date(dmy[2], dmy[1] - 1, dmy[0]);
like image 45
Andy E Avatar answered Sep 04 '25 08:09

Andy E