How to ignore time-zone on new Date()?
Asked Answered
M

3

8

I have JavaScript function called updateLatestDate that receive as parameter array of objects.

One of the properties of the object in array is the MeasureDate property of date type.

The function updateLatestDate returns the latest date existing in array.

Here is the function:

function updateLatestDate(sensorsData) {
    return new Date(Math.max.apply(null, sensorsData.map(function (e) {
        return new Date(e.MeasureDate);
    })));
}

And here is the example of parameter that function receive:

[{
    "Address": 54,
    "AlertType": 1,
    "Area": "North",
    "MeasureDate": "2009-11-27T18:10:00",
    "MeasureValue": -1
  },
  {
    "Address": 26,
    "AlertType": 1,
    "Area": "West",
    "MeasureDate": "2010-15-27T15:15:00",
    "MeasureValue": -1
  },
  {
    "Address": 25,
    "AlertType": 1,
    "Area": "North",
    "MeasureDate": "2012-10-27T18:10:00",
    "MeasureValue": -1
  }]

The function updateLatestDate will return MeasureDate value of last object in the array.

And it will look like that:

 var latestDate = Sat Oct 27 2012 21:10:00 GMT+0300 (Jerusalem Daylight Time)

As you can see the time of the returned result is different from the time of the input object.The time changed according to GMT.

But I don't want the time to be changed according to GMT.

The desired result is:

 var latestDate = Sat Oct 27 2012 18:10:00 

Any idea how can I ignore time zone when date returned from updateLatestDate function?

Margy answered 18/4, 2016 at 14:35 Comment(5)
What do you mean when it look like that ? In your debogguer ? In what the user see ?Amur
Use moment library it is the bestExtrusive
@Amur yeas in debugger.Later I send the value to the serverMargy
@Extrusive is the any way to solve this problem without using library?Margy
@Margy So your input will be "Sat Oct 27 2012 21:10:00 GMT+0300" and output will be "Sat Oct 27 2012 23:40:00"Extrusive
D
3

As Frz Khan pointed, you can use the .toISOString() function when returning the date from your function, but if you're seeking the UTC format, use the .toUTCString(), it would output something like Mon, 18 Apr 2016 18:09:32 GMT

function updateLatestDate(sensorsData) {
    return new Date(Math.max.apply(null, sensorsData.map(function (e) {
        return new Date(e.MeasureDate).toUTCString();
    })));
}
Dissonancy answered 18/4, 2016 at 18:11 Comment(1)
Thank you for answer @Chris. Just a side note. I think you should link to MDN instead of w3schools. Cheers.Tendency
D
0

The Date.toISOString() function is what you need try this:

var d = new Date("2012-10-27T18:10:00");
d.toISOString();

result:

"2012-10-27T18:10:00.000Z"
Denunciate answered 18/4, 2016 at 14:59 Comment(0)
E
-3

If you use moment it will be

moment('Sat Oct 27 2012 21:10:00 GMT+0300', 'ddd MMM DD DDDD HH:mm:SS [GMT]ZZ').format('ddd MMM DD YYYY HH:mm:SS')
Extrusive answered 18/4, 2016 at 14:48 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.