1

I want to parse date in the format ddMMyyhhmm (eg 2804121530 representing 28th April 2012, 3:30 PM) to javascript Date() object.

Is there any oneliner solution to it? I'm looking for something of the kind:

var date = Date.parse('2804121530', 'ddMMyyhhmm');

or

var date = new Date('2804121530', 'ddMMyyhhmm'); 

Thanks for help!

thar45
  • 3,518
  • 4
  • 31
  • 48
James
  • 1,237
  • 2
  • 20
  • 32
  • 2
    There is no such built-in function, but you can have a look at [this question](http://stackoverflow.com/questions/476105/how-can-i-convert-string-to-datetime-with-format-specification-in-javascript) – Miaonster Aug 29 '12 at 05:29
  • 1
    Hi bellow link can be useful for you http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript – vyas pratik Aug 29 '12 at 05:32

3 Answers3

2

For a fast solution you can brake that string into pieces and create date from those pieces

function myDateFormat(myDate){
    var day = myDate[0]+''+myDate[1];
    var month = parseInt(myDate[2]+''+myDate[3], 10) - 1;
    var year = '20'+myDate[4]+''+myDate[5];
    var hour = myDate[6]+''+myDate[7];
    var minute = myDate[8]+''+myDate[9];
    return new Date(year,month,day,hour,minute,0,0);
}

var myDate = myDateFormat('2804121530');

or a simper solution:

function myDateFormat(myDate){
    return new Date(('20'+myDate.slice(4,6)),(parseInt(myDate.slice(2,4), 10)-1),myDate.slice(0,2),myDate.slice(6,8),myDate.slice(8,10),0,0);
}
var myDate = myDateFormat('2804121530');
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
  • 1
    You need to `+ 1` the month (it is zero based), so you have to parse at least that (sorry - -1 `:/`). Also, you could use [string.slice](http://stackoverflow.com/q/2243824/7586) to remove some ugliness. – Kobi Aug 29 '12 at 05:40
  • 2
    added `-1` :) because `Date` starts from 0 – Mihai Iorga Aug 29 '12 at 05:42
2

A useful library here is DateJs. Just add a reference:

<script src="http://datejs.googlecode.com/files/date.js"
        type="text/javascript"></script>

and use Date.parseExact:

var dateStr = '2804121530';
var date = Date.parseExact(dateStr, 'ddMMyyHHmm');
Kobi
  • 135,331
  • 41
  • 252
  • 292
0
(new Date(1381344723000)).toUTCString() 

Correct me if 'm worng...

Govind Malviya
  • 13,627
  • 17
  • 68
  • 94
thar45
  • 3,518
  • 4
  • 31
  • 48
  • James has the *string* `'2804121530'`, so I don't think this helps much. – Kobi Aug 29 '12 at 05:36
  • Right, and I guess the param is seconds/milliseconds since epoch. In my case it's a date string in the format ddMMyyhhmm – James Aug 29 '12 at 05:59