Reputation: 207
I have written ServerSide JavaScript in Xpages as following below, date format is "mm/dd/yyyy"
var date1:NotesDateTime=session.createDateTime("10/15/2013")
var date2:NotesDateTime=session.createDateTime("01/02/2014")
if(date1 <= date2)
{
return "Pass"
}
else
{
return "Fail"
}
Here I should get "Pass", but I am getting "Fail" ??????
Upvotes: 0
Views: 1861
Reputation: 8086
Use the timeDifference
method of NotesDateTime
to compare date instances, not standard operators like <
or >
:
if (date1.timeDifference(date2) < 0) {
return "Pass";
} else {
return "Fail";
}
NOTE: the above can also be expressed more succinctly using the conditional operator:
return (date1.timeDifference(date2) < 0) ? "Pass" : "Fail";
The timeDifference
method essentially "subtracts" the date passed to it from the date instance upon which the method is called, returning the difference in seconds.
So, in the above example, if date2
is later than date1
, the method will return a negative number; if date1
is later than date2
, the result will be a positive number; the result will be 0
if both objects represent precisely the same date and time.
BONUS INFO:
The reason standard comparison operators cannot be used to identify a quantitative difference between the values of these two variables is because the variables are pointers to "objects", not "primitive" values.
JavaScript is an almost entirely typeless language, so the equality operator (==
) is generally only reliable when used to compare strings, numbers, and booleans, and the comparison operators (<
, >
, etc.) are generally only reliable when used to compare numbers. Nearly everything else can be considered an object (including arrays).
Variables with a primitive numeric value are merely pointers to the current value. As a result, the following expression will return true
:
1 <= 2
But the following expression can never be true:
date1 <= date2
...unless at some point you explicitly set both variables to be pointers to the same object:
date1 = date2
Because these are objects, <=
does not compare the values they represent. The =
checks to see if they are pointers to the exact same in-memory object. Unless the operands are primitive, the <
half of the operator is meaningless, because two object variables can never be "less" than each other, they can only either be pointers to the same object or pointers to different objects; the former would make them "equal", the latter would not, even if the two objects identified by the two variables store an identical internal value. They are separate memory allocations, so JavaScript does not consider them to be equal to each other and cannot compare their values using standard comparison operators.
Upvotes: 6