Luke Shinn
Luke Shinn

Reputation: 346

Compare Dates With Null Values JavaScript

Desired Output: I have a date variable being passed that needs to be compared to today's date and return weather it is before or after today. I would then like to return "Yes" or "No" to indicate weather it is active or not.

<script>
    function calculate(currentlyEffective) {

        var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
        var expDate = currentlyEffective.Expiration_Date;
        expDate = new Date(expDate).toUTCString();
        var result = "";

        if (expDate < now_utc) {
            result = "No"
        }
        else {
            result = "Yes"
        }
        return result;
    }

</script>

Problem:

  1. Some of the dates being passed do not have a value because they are not expired yet. This returns Thu, 01 Jan 1970 00:00:00 GMTThe desired output would be "Yes" here even though the date would be less than today because it has no expiration date making it "Yes" still active.

  2. Something isn't happening correctly in the calculation. My return value is always "Yes"

Questions:

  1. Am I comparing these dates correctly with my if else function?

  2. Even in an instance where I have a date in expDate that is before today I still get "Yes" as my return value. What am I doing wrong?

Upvotes: 0

Views: 5079

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138257

Youre comparing a string and a Date Object with < ? What do you expect? You dont need the time string, you need the time as a number:

var now=new Date().getTime();//current time as number (ms since...)
var old=new Date(timestring).getTime();//time as number with a timestring ("12:20 ...")
if(now<old){
 alert("future date!");
}

Full code:

    function calculate(currentlyEffective) {

    var now = new Date().getTime();
    var expDate = currentlyEffective.Expiration_Date;
    expDate = new Date(expDate).getTime();

    return expDate<now?"Yes":"No";
}

As RobG pointed out, this can be shortified, as using < on two objects, trys to convert them to number, wich does in fact call getTime:

var calculate=(currentlyEffective)=>new Date(currentlyEffective.Expiration_Date)<new Date()?"Yes":"No";

Upvotes: 1

Related Questions