0

I get from data base this date string:

var MeasureDateStr = "2016-07-19T16:29:31";

On client I create datetime javascript object from MeasureDate value:

var measureDate = new Date(MeasureDateStr);

After the measureDate object is created the content is:

var measureDate = Tue Jul 19 2016 19:29:31 GMT+0300 (Jerusalem Daylight Time);

As you can see I have different time (+3 hours) relatively to original date string.

My question is why I get diffrent time in measureDate and how to fix the problem?

Michael
  • 13,950
  • 57
  • 145
  • 288

3 Answers3

0

You get user local time because you don't have anything to tell browser in which timezone to look at.

If you want to have UTC time, just add Z at the end of time string:

var MeasureDateStr = "2016-07-19T16:29:31Z";

Also this may help: How to ISO 8601 format a Date with Timezone Offset in JavaScript?

Community
  • 1
  • 1
0

It's because your browsers timezone is set to GMT+3. And since you do not specify a timezone in your datestring it will add 3 hours automatically.

EDIT:

var d = '2016-07-19T16:29:31';
var offset = new Date().getTimezoneOffset() * 60 * 1000; // get Timezone offset in milliseconds.
d = new Date(Date.parse(d) + offset) // Remove the timezone offset.

console.log(typeof d); // object
console.log(d); // Tue Jul 19 2016 16:29:31 GMT+0200 (CEST)

Old answer:

new Date('2016-07-19T16:29:31').toUTCString()
Jonathan Nielsen
  • 1,442
  • 1
  • 17
  • 31
0

Are you sure? The string you are reporting is a local time string.

If I run your example, I get a Tue Jul 19 2016 16:29:31 GMT+0200 (ora solare Europa occidentale), so the local time is preserved, while a time zone is attached.

If you add a Z, or a time zone indication (like 2016-07-19T16:29:31+03:00), you can specify exactly the behaviour you want.

Please note that when you log the date, you will always get a local format, even if the date was specified with another time zone:

var MeasureDateStr = "2016-07-19T16:29:31+03:00";
var measureDate = new Date(MeasureDateStr); 
console.log(measureDate);

I get Tue Jul 19 2016 15:29:31 GMT+0200 (ora solare Europa occidentale) because I'm on GMT+2. But the time is converted accordingly.

Alberto Chiesa
  • 7,022
  • 2
  • 26
  • 53