FAQ Topic - How can I create a Date from a String? (2009-08-09)

F

FAQ server

-----------------------------------------------------------------------
FAQ Topic - How can I create a Date from a String?
-----------------------------------------------------------------------

An Extended ISO 8601 local Date format ` YYYY-MM-DD ` can be parsed to a
Date with the following:-

/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* @param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* @return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*([\d]{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);

if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
} else {
date.setHours(0, 0, 0, 0);
}
}
return date;
}


The complete comp.lang.javascript FAQ is at
http://jibbering.com/faq/
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
, Sat, 8 Aug 2009 23:00:02, FAQ server <[email protected]> posted:

An Extended ISO 8601 local Date format ` YYYY-MM-DD ` can be parsed to a
Date with the following:-

/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* @param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* @return {Date} Date object representing the string.
*/

But new Date(), in IE8, parses "55/55/5555" to Aug 24 5559, quite
happily.

There are two conditions to consider in the explanation :
whether it matches the yyyy-mm-dd pattern
whether the actual digits correspond to a genuine
astronomical proleptic Gregorian date.

I would like to see different indications being given for the two types
of error.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top