Link to home
Start Free TrialLog in
Avatar of Conrado ZAVALA
Conrado ZAVALAFlag for Honduras

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.
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
<script>
var d = new Date("07/31/2014");
alert(d);
</script>

Open in new window

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

Open in new window

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
As Ray has indicated you can see this on Mozilla
dateString
A string representing an RFC2822 or ISO 8601 date (other formats may be used, but results may be unexpected).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
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
var removeMonthFromDate = function(mmDDYYY, monthToRemove) {
   var arr = mmDDYYY.split("/");
   return new Date(arr[2],arr[0]-1-monthToRemove,arr[1]);
}

Open in new window


I can do : removeMonthFromDate("07/31/2014", 60); // 5 years ago

http://jsfiddle.net/bf8med9w/