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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Michael
  • 13,950
  • 57
  • 145
  • 288

3 Answers3

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();
    })));
}
Chris Jaquez
  • 649
  • 1
  • 6
  • 16
  • Thank you for answer @Chris. Just a side note. I think you should link to [MDN](https://developer.mozilla.org/en-US/) instead of w3schools. Cheers. – Simão Garcia Jul 18 '19 at 14:06
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"
Frz Khan
  • 218
  • 3
  • 8
-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')
Devank
  • 159
  • 2
  • 9