mattc19
mattc19

Reputation: 718

sending javascript date object to server without adjusting for time zone difference

Is there a way to send data from the client to a server without adjusting the time to account for the time zone difference between the client and server?

I have an angular app with a nodejs server. When I send a date from a form to the server via an HTTP request and log the date on the server, the date changes to the time in the time zone of the server.

I'd like to send the date object back and forth without it changing.

Upvotes: 2

Views: 5750

Answers (3)

Brass
Brass

Reputation: 56

According to MDN Javascript Date objects are constructed using UTC.

You can send the date object back and forth without ever changing it, it will simply be interpreted relative to the 'locale' of wherever it is being used.

If you'd like to maintain the local date and time irrespective of location (between different client and server locations) you'll probably need to pass along the locale of the Date as well as the Date itself.

A way to do this is to format your Date as a string in ISO 8601 format with a time offset (like +0100.) That way you'll get both the local time and the offset used for every time.

You can construct it by hand using the Date.prototoype.toISOString method but that will still be relative to UTC.

Here's another Stack Overflow question on how to get the correct offset yourself.

Upvotes: 1

Richard.Davenport
Richard.Davenport

Reputation: 1501

I always use http://momentjs.com/ when dealing with javascript dates. When a date object is created the systems timezone is used, so you'll always have to adjust for the offset. The easiest solution is to do one of the following

  • use a string and parse it
  • use moment().format() with a custom format
  • use UTC on the client and server
  • use ticks or unix epoch

There really isn't a great solution, you just need to be consistent.

Upvotes: 4

Vamshi
Vamshi

Reputation: 9341

Use milliseconds .

let now = new Date();
let time = now.getTime(); 

time contains number of milliseconds in UTC timezone always. In the server you can convert milliseconds to date . This way you dont need to worry about timezones.

Upvotes: 3

Related Questions