Reputation: 841
I want to create a Date object in Javascript using this string 04/21/2014 12:00p
When passed to the constructor (new Date('04/21/2014 12:00p')
), it returns Invalid Date
.
I've seen other posts which manipulate the string in order to fulfill the requirements of a valid dateString, however that is not what I want. I want Javascript to recognize my date format (m/dd/yy h:mmt
). In Java, something like that is simple, I imagine that there would be a similar way in Javascript.
How can I get the Date object to recognize my format?
Upvotes: 2
Views: 12562
Reputation: 241420
This is trivial only when using a library like moment.js:
var dt = moment("04/21/2014 12:00p","MM/DD/YYYY h:mma").toDate();
Otherwise, you would have considerable string manipulation to do. Also you would have to account for users in parts of the world that use m/d/y or other formatting instead of the y/m/d formatting of your input string.
If this string is being sent from some back-end process, you might consider changing the format to a standard interchange format like ISO-8601 instead. Ex. "2014-04-21T12:00:00"
Upvotes: 4
Reputation: 1907
if (String.prototype.dateFromJava == null)
{
String.prototype.fromJava = function (sDateString)
{
var aDateOrTime = sDateString.splt(" ");
var aDateParts = aDateOrTime[0].split("/");
var aTimeParts = aDateOrTime[1].split(":");
var oDate = null;
/* just get the pieces and passing them in to new Date(), return oDate */
}
}
Upvotes: 0