JavaScript doesn't tell you the Date object is bad, here's how to figure that out before crashing your program

In JavaScript, creating a Date object from a string is real convenient ("var foo = new Date(dateString)"), but what if dateString has a bad format? How will your code know about this? The Date object doesn't have a getter to tell you the date is bad.

In AkashaCMS I just added a feature so the website author can set the file date using metadata in the content. Previously the file date was set from the date code on the input file, but of course that's probably not accurate. It's better if the website author can specify the date they want to appear in the website, and as the file date.

I thought it was going to be easy:

var atime = entry.stat.atime;
var mtime = entry.stat.mtime;
if (entry.frontmatter.publDate) {
     atime = mtime = new Date(entry.frontmatter.publDate);
}
fs.utimes(renderTo, atime, mtime, function(err) {
     add_sitemap_entry(options.root_url +'/'+ rendered.fname, 0.5, mtime);
     done();
});

You don't do this

atime = mtime = Date.parse(entry.frontmatter.publDate);

because Node.js uses a Date object rather than the number-of-miliseconds-since-Jan-1-1970 value.

Sure enough, with a good date string this worked. Then I decided to do as good programmers do, and give it a bad date string to see what would happen.

$ ls -l out/about.html
Segmentation fault: 11

Hey Apple, it's really bad for the operating system to allow the date code in the file to be so bad that it crashes software.

Then adding a little bit of debugging output I learned this:

4 May 20:39:40 - set out/about.html file date to Invalid Date

So, the Date object knows that it's invalid, but there is no method to inform the programmer of the invalid Date.

After some thinking I decided it'd be best to parse the date string first, then inspect that result to see if it's a valid number, and only then create the Date object.

var atime = entry.stat.atime;
var mtime = entry.stat.mtime;
if (entry.frontmatter.publDate) {
     var parsed = Date.parse(entry.frontmatter.publDate);
     if (isNaN(parsed)) {
            util.log("WARNING WARNING Bad date provided "+ entry.frontmatter.publDate);
     } else {
            atime = mtime = new Date(parsed);
     }
}
fs.utimes(renderTo, atime, mtime, function(err) {
     add_sitemap_entry(options.root_url +'/'+ rendered.fname, 0.5, mtime);
     done();
});

Note - this code is written for Node.js, but the concept should be applicable if your JavaScript is running in a browser.

When given a bad date string, Date.parse returns NaN. So, detecting that condition then lets me either use the parsed date, or not. Q.E.D.