Conrado ZAVALA
asked on
Convert a string into date with javascript or jquery.
Dear Experts,
I have this string "07/31/2014" and I want to convert that string into a date.
How can I do this with javascript or jquery?
Thanks in Advance.
Best Regards.
I have this string "07/31/2014" and I want to convert that string into a date.
How can I do this with javascript or jquery?
Thanks in Advance.
Best Regards.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
The following returns a number. I've found this very flexible for comparing dates, storing in databases and it's easily formatted when you need it.
var d = Date.parse("07/31/2014");
alert(d); // returns the number of milliseconds since January 1, 1970
It's also important to note that these functions do NOT support the European/Australian date format dd/mm/yyyy and in that case I would recommend using a library like datejs (http://www.datejs.com) or parsing it yourself. The important thing is you have to be aware of the format and not mix them unknowingly.
OT, but if you have the PHP scripting language date conversions are very easy. The principles about ISO-8601 standards are applicable to all languages.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html
As Ray has indicated you can see this on Mozilla
dateStringhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
A string representing an RFC2822 or ISO 8601 date (other formats may be used, but results may be unexpected).
And one other note... JavaScript was created in about 2 months time, in a dead-heat race for a finished language. As a result there are some oddities in JavaScript, to be sure. The "month" number returned by JavaScript functions is zero-based, with zero being January and 11 being December. Nobody writes calendar dates that way (except JavaScript). You do not have to worry about this anomaly if you're using the new Date() notation, but it's worth being aware of it when you retrieve fractional parts of a date value or attempt arithmetic.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth
var removeMonthFromDate = function(mmDDYYY, monthToRemove) {
var arr = mmDDYYY.split("/");
return new Date(arr[2],arr[0]-1-monthToRemove,arr[1]);
}
I can do : removeMonthFromDate("07/31
http://jsfiddle.net/bf8med9w/
Open in new window