Reputation: 8941
I'm creating a little webserver in node.js. Currently the server uses new Date() to get the current time. That worked fine when I ran the server on my development machine. But once I deployed the server to a web hoster (in some other country), I got the wrong time.
How can a node.js server get the current time in my country (including daylight saving time offset)?
If possible, without involving some external servers, like the Google time API.
Upvotes: 1
Views: 479
Reputation: 2452
Javascript date only understands the time local to the environment, or UTC. This is a fundamental limitation of the date object, and there is no built-in way around it.
If you always want the server to return the time in a different timezone, then you could include the moment timezone timezone library. It will convert a date local to the server into a timezone of your choice.
In order to do this, you have to convert all of your dates to moments, but for most people this isn't an issue.
To get the current time in the America/Los_Angeles timezone:
moment().tz("America/Los_Angeles").format()
"2016-03-18T19:57:22-07:00"
Note that the current time where I am is "2016-03-18T21:58:05-05:00". The date has been shifted back two hours to reflect the time difference.
This is a dependency of course, but there is no external server involved.
Moment TimeZone's node documentation can be found here: http://momentjs.com/timezone/docs/#/use-it/node-js/
Upvotes: 1