views:

465

answers:

2

Hi all,

i want to convert this string 23/08/2009 12:05:00 to javascript datetime

how can i do it?

+2  A: 

I think this can help you http://www.mattkruse.com/javascript/date/

Theres a getDateFromFormat() function that you can tweak a little to solve your problem.

Lucas McCoy
@lucas and what about the time is there a way to parse it too?
avnic
The parse function doesn't accepts this format, try it, in IE and FF you will get **Mon Nov 08 2010 12:05:00**, in Chrome just **Invalid Date**
CMS
@CMS: It was a first guess. I found a different method. Thanks.
Lucas McCoy
+2  A: 

You can get the parts of the date using a regex, and call the Date constructor, adjusting the month number, since the month numbers are zero based, for example:

function customDateParse (input) {
  var m = input.match(/(\d+)/g);
  return new Date(m[2], m[1] - 1, m[0], m[3], m[4], m[5]);
}

customDateParse('23/08/2009 12:05:00');
// Sun Aug 23 2009 12:05:00

If you don't like regexps:

function customDateParse (input) {
  input = input.split(' ');
  var date = input[0].split('/'),
      time = input[1].split(':');

  return new Date(date[2], date[1] - 1, date[0], time[0], time[1], time[2]);
}

customDateParse('23/08/2009 12:05:00');
// Sun Aug 23 2009 12:05:00

But if you find that complex and you are willing to do more Date manipulations I highly recommend you the DateJS library, small, opensource and syntactic sugar...

CMS
That seems a bit complex. It also seems like an over use of Regex since there is a `getDateFromFormat()` method available in JavaScript.
Lucas McCoy
There is no native *getDateFromFormat* function...
CMS
See the link I provided in my answer.
Lucas McCoy
Oh, haven't seen the link...
CMS
@Lucas: refined the regexp...
CMS
+1 for DateJS. I have used it, and it's great.
Daniel Yankowsky