ToISOString () changes the date and time value

I have an array of objects. Each object in the array has a date property. I am trying to get the largest (last) date from an array.

Here is the 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 the function: select the largest date from the array above:

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

The result that I get from the function updateLatestDateis:

2017-08-20T06:56:13.000Z

but this is strange, because since you do not see any of the properties in the sensorData objects, there is no date returned from the function updateLatestDate.

Here is the FIDDLER .

Any idea why the updateLatestDate function returns an incorrect result?

+4
source share
2 answers

new Date(str), . toISOString() UTC, "Z".

:

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

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

getTimezoneOffset , new Date 1 1970 00:00:00 UTC, 60000 .

+8

, ( , ) , int, ,

<button onclick="setDate()">irreversible conversion</button>
<script>
   
function setDate(){
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"}];

function irreversible(){
          sensorsData.forEach(function (e){
            console.log(
                 new Date(
                      new Date(e.MeasureDate).getTime()
                 )
             );
          })        
        } 
        
        irreversible();
}        

</script>
Hide result

: ,

function setDate(){
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"}];

var lastDate = updateLatestDate(sensorsData);
console.log(lastDate.MeasureDate);


function compare(d1,d2){
if (d1.MeasureDate >d2.MeasureDate)
  return d1;
else
  return d2;
}

function updateLatestDate(sensorsData) {
      return ( sensorsData.reduce(compare) );
  }
}
</script>
<button onclick="setDate()">update date</button>
Hide result
0

Source: https://habr.com/ru/post/1684056/


All Articles