Let's assume I have a proper Date
object constructed from the string: "Tue Jan 12 21:33:28 +0000 2010"
.
var dateString = "Tue Jan 12 21:33:28 +0000 2010";
var twitterDate = new Date(dateString);
Then I use the <
and >
less than and greater than parison operators to see if it's more or less recent than a similarly constructed Date
. Is the algorithm for paring dates using those operators specified, or is it specifically unspecified, like localeCompare
? In other words, am I guaranteed to get a more recent date, this way?
var now = new Date();
if (now < twitterDate) {
// the date is in the future
}
Let's assume I have a proper Date
object constructed from the string: "Tue Jan 12 21:33:28 +0000 2010"
.
var dateString = "Tue Jan 12 21:33:28 +0000 2010";
var twitterDate = new Date(dateString);
Then I use the <
and >
less than and greater than parison operators to see if it's more or less recent than a similarly constructed Date
. Is the algorithm for paring dates using those operators specified, or is it specifically unspecified, like localeCompare
? In other words, am I guaranteed to get a more recent date, this way?
var now = new Date();
if (now < twitterDate) {
// the date is in the future
}
Share
Improve this question
edited Nov 8, 2012 at 14:34
Denys Séguret
383k90 gold badges811 silver badges776 bronze badges
asked Nov 8, 2012 at 8:45
wwaawawwwaawaw
7,13710 gold badges35 silver badges42 bronze badges
1
- Yes you will get most recent date this way – polin Commented Nov 8, 2012 at 8:53
3 Answers
Reset to default 8Relational operations on objects in ECMAScript rely on the internal ToPrimitive function (with hint number) that you can access, when it is defined, using valueOf.
Try
var val = new Date().valueOf();
You'll get the internal value of the date which is, as in many languages, the number of milliseconds since midnight Jan 1, 1970 UTC (the same that you would get using getTime()
).
This means that you're, by design, ensured to always have the date parison correctly working.
This article will give you more details about toPrimitive
(but nothing relative to parison).
Date values in Javascript are numbers, as stated in the ECMA Script specification. So the Date values are pared as numbers.
This is a demo of your code (I set twitterDate in the future).
(function(){
var dateString = "Tue Jan 12 21:33:28 +0000 2014";
var twitterDate = new Date(dateString);
var now = new Date();
if (now < twitterDate) {
document.write('twitterDate is in the future');
}
else
{
document.write('twitterDate is NOT in the future');
}
})()
I think yes. Using if (now < twitterDate)
, it evaluates to if (now.valueOf()<twitterDate.valueOf())
. valueOf()
delivers the number of milliseconds passed since 01/01/1970 00:00:00, so the parison of those 2 numbers is valid.
check it like this
var then = new Date("Tue Jan 12 21:33:28 +0000 2010")
,now = new Date;
console.log(then.valueOf(),'::',now.valueOf(),'::',now<then);
//=> 1263332008000 :: 1352365105901 :: false