0

I have a string of format YYMMDDHHMMSS. How to create a js date object from this pattern? Is there any built in method for this? Or I have to create split the string into array of string (each of length 2 characters) then used in new Data object?

coure2011
  • 40,286
  • 83
  • 216
  • 349
  • 1
    Possible duplicate of http://stackoverflow.com/questions/476105/how-can-i-convert-string-to-datetime-with-format-specification-in-javascript – Aleks G Jan 11 '12 at 15:16

3 Answers3

0

Simplest to just parse out each date part and pass them in the correct order to the Date constructor;

var s = "120109123456";
var d = new Date(2000 + +s.substr(0, 2),
    s.substr(2, 2) - 1,
    s.substr(4, 2),
    s.substr(6, 2),
    s.substr(8, 2),
    s.substr(10, 2));

(Assumes this century)

Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

You can use a regexp to split the string then set the Date properties, something like this:

var s_date = "720417121253"; //YYMMDDHHMMSS
var parts = s_date.match(/\d{2}/g);
var date =  new Date();
date.setYear(parts[0]);
date.setMonth(parts[1]);

Note that you use 2 digits for the year, which is a bit problematic

Shlomi Schwartz
  • 8,693
  • 29
  • 109
  • 186
0
var d = new Date;
var methods = ['Year','Month','Date','Hours','Minutes','Seconds'];
var time = "120111120001";
for(var i=0,j=0;i<methods.length;i++,j+=2) {
  var method = 'set'+methods[i];
  var split = time.substr(j,2);
  d[method](split);
}
matsko
  • 21,895
  • 21
  • 102
  • 144