views:

36

answers:

3

Hi there,

Can anyone inform me of the best way to get the current date/time in seconds in javascript?

+1  A: 

Based on your comment, I think you're looking for something like this:

var timeout = new Date().getTime() + 15*60*1000; //add 15 minutes;

Then in your check, you're checking:

if(new Date().getTime() > timeout) {
  alert("Session has expired");
}
Nick Craver
+1 for a practical solution :-)
Andy E
+3  A: 
var seconds = new Date().getTime() / 1000;

....will give you the seconds since mindnight, 1 Jan 1970

Ref

sje397
While this is accurate, when would it ever be useful? :)
Nick Craver
@Nick - this is [Unix time](http://en.wikipedia.org/wiki/Unix_time)
sje397
@sje397 - Yes...but the question (like most on SO) is most likely to solve a *practical* problem, can you give me an example where you'd want to display this result?
Nick Craver
@Nick - I think all examples are necessarily speculative and will sound contrived - but I'll take a shot :) Suppose you have data time stamped with unix time, and want to determine it's age. More though I think this is what is most likely meant by 'the current date/time in seconds'; just my gut feeling.
sje397
When a Date object's *valueOf()* method is called, it returns a number representation. That means that you can completely do away with *getTime()* if you want, since the division mathematical operator will force to a Number via the *valueOf()* method. So your code is exactly the equivalent of `var seconds = new Date() / 1000;`. FWIW ;-)
Andy E
@Nick: It's very useful when calculating time and timespans. For example: No need to worry if the month is 28, 29, 30 or 31 days or if the year has 365 or 366 days... It might not be very readable for humans, but that is easily converted.
some
+2  A: 

To get the number of seconds from the Javascript epoch use:

date = new Date();
milliseconds = date.getTime();
seconds = milliseconds / 1000;
Lazarus