Can I make node.js Date always be in UTC/GMT?

前端 未结 2 1380
我在风中等你
我在风中等你 2020-12-30 00:08

My app runs on Linux servers, where the time (naturally) set to UTC/GMT. However the app is developed on Mac desktops where the time is typically set to a local timezone.

相关标签:
2条回答
  • 2020-12-30 00:28

    You can use TZ configuration parameter of node.js as follows.

    For bash (and related)

    export TZ=UTC
    

    For Powershell

    $env:TC = 'UTC'
    

    Then for both:

    nodejs server/index.js
    
    0 讨论(0)
  • 2020-12-30 00:35

    From the MDN docs on Date#getTime:

    The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.

    Assuming you're storing dates/times as numbers (which I would recommend), getTime is already UTC, always.

    Suppose your client then requests a date from the server. If the server provides the date as timestamp, which is a number, the client can then do:

    new Date(timestamp);
    

    And it will be correctly adjusted to the local time on the client.

    Of course, maybe I'm misunderstanding your problem. But I just want to point out that this...

    new Date().getTime() + new Date().getTimezoneOffset();
    

    ...should never really make sense. It's taking a UTC-based time and then offsetting it further, in essence double-offsetting a time.

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