我的javascript(node.js)如何给我不正确的时间戳? [英] How come my javascript (node.js) is giving me the incorrect timestamp?

查看:105
本文介绍了我的javascript(node.js)如何给我不正确的时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制台中输入日期,我得到 Tue Sep 20 01:01:49 PDT 2011 ...这是正确的。



但是我在node.js中执行此操作,而且我收到错误的时间。

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

输出是:1316505706,这是一小时后。

解决方案

@KARASZI是绝对正确的根本原因:Unix时间戳始终是UTC,除非你操纵它们。我建议,如果你想要一个Unix时间戳,你应该把它留在UTC,只有转换到本地时间,如果你需要显示格式化的时间给用户。



这样做的第一个好处是,所有的服务器都可以在同一时间说话。例如,如果您将服务器部署到Amazon EC2 US East和Amazon EC2 US West,并且共享一个通用数据库,则可以在数据库和服务器上使用UTC时间戳,而不必担心每次都会出现时区转换。这是使用UTC时间戳的一个很好的理由,但可能不适用于您。



这样做的第二个好处是您可以根据经过的时间测量事物,而不会不必担心夏令时间(或时区,如果您正在移动的平台上测量时间)。这不是很多,但是如果你有某种情况发生了消极的时间,因为当地时间在你测量的时候回落了一个小时,你会很困惑!



我可以想到的第三个原因很小,但是一些性能极客将非常感激:您可以获得原始的UTC时间戳,而不必每次分配一个新的Date对象,通过使用Date类的now 功能。

  var ts = Date.now()/ 1000; 


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.

解决方案

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

这篇关于我的javascript(node.js)如何给我不正确的时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆