我的javascript(node.js)如何给我不正确的时间戳?

编程入门 行业动态 更新时间:2024-10-11 09:21:37
本文介绍了我的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)如何给我不正确的时间戳?

本文发布于:2023-11-27 11:23:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637857.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:给我   不正确   时间   javascript   node

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!