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

前端 未结 4 1599
攒了一身酷
攒了一身酷 2021-01-12 02:39

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.

4条回答
  •  不要未来只要你来
    2021-01-12 03:26

    @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;
    

提交回复
热议问题