28

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

I could change every new Date() in my code to run:

var date = new Date().getTime();

And thus ensure dates on the server are always GMT, but that seems inelegant.

I understand previous versions of node used to always return UTC/GMT. Is there any way to bring this behavior back?

Edit: Removed adding timezone offset to getTime() per comments - since getTime() is already in UTC.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
  • 1
    I think that old behavior was just the way the REPL code worked. You can always use the UTC APIs in your own code if you want. – Pointy Aug 18 '14 at 16:27
  • @pointy is there any way to make UTC the default when `new Date()` is ran? – mikemaccana Aug 18 '14 at 16:29
  • You can *always* get the UTC date from a Date instance. Other than keeping the underlying platform set with UTC as the local time zone, however, I don't know of a way to tell the JavaScript runtime (node) to do that for you. – Pointy Aug 18 '14 at 16:32
  • 1
    `getTime()` will always return the ms since the epoch in UTC. Adding the current time zone offset is never a good idea. – Matt Johnson-Pint Aug 18 '14 at 16:39

2 Answers2

42

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
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Er. Mohit Agrawal
  • 2,116
  • 1
  • 17
  • 15
  • 1
    Great, thanks! One note, when running unit tests with Mocha that test dates, I needed to run it like `export TZ=UTC; mocha --recursive test`. Though `export TZ=utc` works to change the time zone to UTC, the CI box writes it uppercased as `UTC` —important if you do a date string assertion. – Tina Jun 11 '16 at 16:51
18

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 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.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Dan Tao
  • 125,917
  • 54
  • 300
  • 447