Michael Michael - 6 months ago 29
Javascript Question

Why function returns wrong date result?

I have array of the objects.Each object in array has date property.I try to get biggest(the last) date from array.

Here is array:

var sensorsData = [{Id:1,MeasureDate:"2017-08-20T09:52:32" },{Id:2,MeasureDate:"2017-08-20T09:54:35" },{Id:3,MeasureDate:"2017-08-20T09:56:13"}];

And here is function the fetch the biggest date from array above:

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

the result that I get from
function is:


but it strange because, as you can see no one of the properties in sensorsData objects doesn't have the date as returned from

Here is FIDDLER.

Any idea why updateLatestDate function returns wrong result?

Answer Source

When you create a date with new Date(str) it creates a date object with a time zone. toISOString() makes it zero UTC offset, as denoted by the suffix "Z".

Here is a workaround:

var date = new Date(e.MeasureDate)
return new Date(date.getTime() - date.getTimezoneOffset() * 60000)

Updated fiddler: https://jsfiddle.net/xf5jmLL6/7

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download