Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come my javascript (node.js) is giving me the incorrect timestamp?

I typed "date" in console...and I get Tue Sep 20 01:01:49 PDT 2011 ...which is correct.

But then I do this in node.js, and I get the wrong time.

 var ts = String(Math.round(new Date().getTime() / 1000));

Output is: 1316505706, which is an hour behind.

like image 703
TIMEX Avatar asked Sep 20 '11 08:09

TIMEX


2 Answers

@KARASZI is absolutely correct about the root cause: Unix timestamps are always UTC unless you manipulate them. I would suggest that if you want a Unix timestamp you should leave it in UTC, and only convert to local time if you need to display a formatted time to the user.

The first benefit of doing this is that all your servers can "speak" the same time. For instance, if you've deployed servers to Amazon EC2 US East and Amazon EC2 US West and they share a common database, you can use UTC timestamps in your database and on your servers without worrying about timezone conversions every time. This is a great reason to use UTC timestamps, but it might not apply to you.

The second benefit of this is that you can measure things in terms of elapsed time without having to worry about daylight savings time (or timezones either, in case you're measuring time on a platform which is moving!). This doesn't come up very much, but if you had a situation where something took negative time because the local time "fell back" an hour while you were measuring, you'd be very confused!

The third reason I can think of is very minor, but some performance geeks would really appreciate it: you can get the raw UTC timestamp without allocating a new Date object each time, by using the Date class's "now" function.

var ts = Date.now() / 1000;
like image 197
mattbornski Avatar answered Nov 01 '22 11:11

mattbornski


The reason is that the getTime function returns the time in the UTC timezone:

The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC. You can use this method to help assign a date and time to another Date object.

If you want to fetch the UNIX timestamp in you current timezone, you can use the getTimezoneOffset method:

var date = new Date();
var ts = String(Math.round(date.getTime() / 1000) + date.getTimezoneOffset() * 60);
like image 41
KARASZI István Avatar answered Nov 01 '22 11:11

KARASZI István