Hacker News new | ask | show | jobs
by biturd 4061 days ago
I was looking at some of the code for one of his projects that is a little node http server. I don't really know JS or node at all, but can someone explain this to me:

     function secondsSince (when) { 
	var now = new Date ();
	when = new Date (when);
	return ((now - when) / 1000);
	}
I'm assuming now returns seconds since some fixed point in time ( epoch ) when when someone passes in the 'when' argument, it must already be formatted a certain way, or node/js somehow managed to figure out the input? How would it deal with 5/8/2015 vs 8/5/2015

Or this is just a very case specific function and the input is already sanitized in a way that is prepared for this function?

github is here: https://github.com/scripting/pagepark/blob/master/lib/utils....

4 comments

new Date () returns creates a JavaScript date object.

When coerced to a number, it's the number of milliseconds since January 1, 1970.

If you wanted to know the number of seconds since January 1, 1970, you could divide by 1000. Since JavaScript will do the coercion for you automatically you can pretty much treat a date object as if it were a number.

This is basically a utility routine that I use for debugging messages to say how long an operation took.

Here's an example of its use:

https://github.com/scripting/myWordEditor/blob/master/script...

It's especially nice because JavaScript automatically does real arithmetic on the division, so you get fractions of seconds displayed in the console.

I use this routine a lot. Helps me spot performance problems. Nice to have, not a crucial routine.

Hope this helps! ;-)

It'll work with any Javascript Date object (passing a Date to the Date constructor just gets you a new object with the same value) or any other value that works in the Date constructor: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
I'm not 100% sure what he's doing here, however I know when I have used new Date().getTime() it returns something like milliseconds, and thus I had to divide by 1000 to result in seconds, so it appears that he's subtracting milliseconds and getting seconds after the division by 1000.

Typically I believe new Date() is current time/date (http://www.w3schools.com/js/tryit.asp?filename=tryjs_date_ne...) in my experience.

As far as your question how to deal with 5/8/2015, and 8/5/2015, to be honest I don't know that answer.

Also assuming I can read, it doesn't look like that function is used, (I searched second in the same file, and in the higher level folder, and couldn't find that function called anywhere)
see the Mozilla JavaScript docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

a Date can be constructed with either a number of milliseconds since the epoch or a string in a format recognised by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601)