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

前端 未结 4 1547
攒了一身酷
攒了一身酷 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:19

    date in console will return the server time, whereas using JavaScript on a webpage will return the client's local time.

    0 讨论(0)
  • @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;
    
    0 讨论(0)
  • 2021-01-12 03:27

    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);
    
    0 讨论(0)
  • 2021-01-12 03:29

    Note you can avoid this confusion by using a node.js package like timezonecomplete or timezone-js which have an interface that is much less error-prone for date and time manipulation.

    0 讨论(0)
提交回复
热议问题