JavaScript Date.parse() and null dates

77,426

Solution 1

parse() returns NaN on an impossible parse so how about just;

 var date = Date.parse(dateString) || 0;

Solution 2

If you're truly looking for comparison of a valid JS Date object (which is 'empty' or unset but therefore defaults Jan 01, 1970) to test whether it's falsey - you can use:

var null_date = new Date(0);

This will create a Date object that is set at the minimum (zero'th) timestamp from where Date() starts counting...which is equivilant to a Date object that has never been set.

Solution 3

You could use isNaN(date) to check for invalid date. Are you sure you want to use "MinValue; from Date? I was running the js on chrome and kept on getting undefined.

Share:
77,426
fearofawhackplanet
Author by

fearofawhackplanet

Updated on July 20, 2022

Comments

  • fearofawhackplanet
    fearofawhackplanet almost 2 years

    I'm trying to sort a list of dates, but I'm struggling with null dates which aren't being handled consistently.

    So I need something like:

    var date = Date.parse(dateString);
    if (!date) {
        date = Date.MinValue;
    }
    

    but I'm struggling to find the correct syntax. Thanks


    Update: The bug turned out to be a different problem. I have Datejs imported for use in another part of the project, so I hadn't realised that Datejs defines a Date.parse() method which was overriding the standard JavaScript method.

    Anyway, it turns out that Datejs has a weird bug which means it doesn't handle dates beginning with "A" properly. So actually my null dates were being ordered correctly, it was just April and August dates were then being mixed up with them.

    The fix is to use the Datejs Date.parseExact method which lets you provide a specific format string, see here.

  • Keerigan
    Keerigan over 11 years
    Personally like this test better, nicer for readability when checking if( !isNaN(date) ) than if( date != 0 )