Tutorial :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?


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


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


I tried your example and it worked fine...

5/27 11:00pm

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


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


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.


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.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »