Jared
Jared

Reputation: 7243

Javascript convert "05/27 11:00pm" to date?

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?

Upvotes: 0

Views: 247

Answers (5)

Jim Davis
Jim Davis

Reputation: 1230

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.

Upvotes: 0

Nosredna
Nosredna

Reputation: 86306

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

Upvotes: 3

Ben Blank
Ben Blank

Reputation: 56624

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, " $&"));

Upvotes: 4

Joe
Joe

Reputation: 2447

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.

Upvotes: 0

Gourneau
Gourneau

Reputation: 12868

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

Upvotes: 1

Related Questions