toISOString()更改日期时间值 [英] toISOString() changes datetime value
问题描述
我有对象的数组。数组中的每个对象都有date属性。我尝试从数组中获取最大(最后)日期。
这里是数组:
var sensorData = [{
Id:1,
MeasureDate: 2017-08-20T09: 52:32
},{
Id:2,
MeasureDate: 2017-08-20T09:54:35
},{
Id:3 ,
MeasureDate: 2017-08-20T09:56:13
}];
这是从上面的数组中获取最大日期的函数:
函数updateLatestDate(sensorsData){
返回新的Date(Math.max.apply(null,sensorsData.map(function(e)){
返回新的Date(e.MeasureDate);
}))))。toISOString();
}
我从 updateLatestDate $得到的结果c $ c>函数是:
2017-08-20T06:56:13.000Z
但这很奇怪,因为如您所见,sensorsData对象中没有一个属性没有从<$ c $返回的日期c> updateLatestDate 函数。
这里是过滤器。
为什么updateLatestDate函数返回错误结果?
使用 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
返回分钟数,新日期
期望自1970年1月1日00:00:00 UTC以来的毫秒数,因此乘以60000可提供所需的调整。 / p>
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);
}))).toISOString();
}
the result that I get from updateLatestDate
function is:
2017-08-20T06:56:13.000Z
but it strange because, as you can see no one of the properties in sensorsData objects doesn't have the date as returned from updateLatestDate
function.
Here is FIDDLER.
Any idea why updateLatestDate function returns wrong result?
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
getTimezoneOffset
returns number of minutes and new Date
expects number of milliseconds since January 1 1970 00:00:00 UTC, so multiplying by 60000 provides needed adjustment.
这篇关于toISOString()更改日期时间值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!