Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

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.

like image 402
mikemaccana Avatar asked Aug 18 '14 16:08

mikemaccana


People also ask

How can I set the default timezone in node JS?

thejh is right, you cannot change the timezone. Use a JS time library (like moment. js) and add / subtract hours instead. The easiest and the correct way to do this is to simply change your system's time zone.

How do you convert date to UTC date?

The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo. ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.

Should date be stored in UTC?

When storing dates in the database, they should always be in UTC. If you are not familiar with what UTC is, it is a primary time standard that all the major timezones are based on. The major timezones are just offsets from UTC.

How can I get the current date and time in UTC or GMT in JavaScript?

JavaScript Date toUTCString() The toUTCString() method returns a date object as a string, according to UTC. Tip: The Universal Coordinated Time (UTC) is the time set by the World Time Standard. Note: UTC time is the same as GMT time.


1 Answers

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 
like image 145
Er. Mohit Agrawal Avatar answered Oct 10 '22 04:10

Er. Mohit Agrawal