tags:

views:

145

answers:

5

How does one convert a string of a date without a year to a JS Date object? And how does one convert a date string with a year and a time into a JS Date object?

A: 

I have used the Dojo time parser to do things like this:

Check it out: http://api.dojotoolkit.org/jsdoc/HEAD/dojo.date.locale.parse

Gourneau
A: 

Not the cleanest, but works:

var strDate = '05/27 11:00pm';
var myDate = ConvertDate(strDate, '2009');

function ConvertDate(strWeirdDate, strYear)
{
    strWeirdDate = strWeirdDate.replace(/ /, '/' + strYear + ' ');
    return new Date(strWeirdDate);
}

Probably want to trim the string first as well.

Joe
+4  A: 

Many different date formats can be converted to date objects just by passing them to the Date() constructor:

var date = new Date(datestring);

Your example date doesn't work for two reasons. First, it doesn't have a year. Second, there needs to be a space before "pm" (I'm not sure why).

// Wed May 27 2009 23:00:00 GMT-0700 (Pacific Daylight Time)
var date = new Date("2009/05/27 11:00 pm")

If the date formats you're receiving are consistent, you can fix them up this way:

var datestring = "05/27 11:00pm";
var date = new Date("2009/" + datestring.replace(/\B[ap]m/i, " $&"));
Ben Blank
Parses fine without space between time and am/pm indicator. Like your solution of just putting year at the start though. Simpler.
Joe
I wondered if that space might be JS-engine-specific. For the record, my copy of FF3 won't parse it without the space ("Invalid date").
Ben Blank
I do have tight control over the format of the date, so this is exactly what I was looking for
Jared
+3  A: 

I'd use the Datejs library's parse method.

http://www.datejs.com/

I tried your example and it worked fine...

5/27 11:00pm

Wednesday, May 27, 2009 11:00:00 PM

Nosredna
I looked at this possibility, but I didn't want to include the whole datejs library just for this one function.
Jared
Datejs is nice when you have very little control over date formats (say, user-supplied, free-text dates). It isn't even that hefty a library if your web host supports compression — only about 7K gzipped.
Ben Blank
A: 

Just another option, which I wrote:

DP_DateExtensions Library

It has a date/time parse method - pass in a mask and it'll validate the input and return a data object if they match.

Also supports date/time formatting, date math (add/subtract date parts), date compare, speciality date parsing, etc. It's liberally open sourced.

Jim Davis