Reputation: 13843
I've written some JavaScript to calculate the difference between two dates, from a twitter stream, and then equate that to a specific value - such as 'Seconds ago', 'x days ago'.....
I've created a Fiddle here that demonstrates what I've done: http://jsfiddle.net/meAEe/3/
However the result is always equal to '0 days ago'.
Can anyone help me figure out why?
Upvotes: 0
Views: 186
Reputation: 5664
Your code is working fine. If you look into your code
var rightNow = new Date("Wed, 21 Dec 2011 13:05:09 +0000");
var then = new Date("Tue, 20 Dec 2011 19:05:09 +0000");
difference is less than 24 hrs and giving 0 days.
I have put
var then = new Date("Mon, 19 Dec 2011 19:05:09 +0000");
It given 1 day ago
Upvotes: 1
Reputation: 16210
That's because you do this: Math.floor(diff / day);
The result of diff / day
is 0.75
. If you round that down, it's 0
. If you change the date, you'll see that your code works just fine.
Upvotes: 0
Reputation: 8690
Aside from some programming details, your problem lies in using Math.floor
function.
According to: http://www.w3schools.com/jsref/jsref_floor.asp
Math.floor actually returns the nearest integer, which in this case is 0, because the results is 0.75.
Upvotes: 0
Reputation: 700342
You need an else
between every if
statement.
Right now it will go into every if
statement following the first that matches. If the time is less than an hour it's also less than two hours, less than a day, less than two days, and less than a year. Each one will replace the previous one, so you only see the last one.
Upvotes: 2
Reputation: 3025
You need to chage the if
s to else if
s (except the first one, of course). Right now they are all evaluated every time.
Upvotes: 0
Reputation: 36999
You have a logic error in your code. The last if statement will always execute because you have not connected your if statements using else if
, which will result in the program execution dropping out once one of the conditions matches.
Upvotes: 1