由于 UTC,JSON Stringify 更改日期时间 [英] JSON Stringify changes time of date because of UTC
问题描述
由于我所在的位置,我在 JavaScript 中的日期对象总是用 UTC +2 表示.于是像这样
My date objects in JavaScript are always represented by UTC +2 because of where I am located. Hence like this
Mon Sep 28 10:00:00 UTC+0200 2009
问题是执行 JSON.stringify
将上述日期转换为
Problem is doing a JSON.stringify
converts the above date to
2009-09-28T08:00:00Z (notice 2 hours missing i.e. 8 instead of 10)
我需要的是兑现日期和时间,但事实并非如此,因此应该是
What I need is for the date and time to be honoured but it's not, hence it should be
2009-09-28T10:00:00Z (this is how it should be)
基本上我用这个:
var jsonData = JSON.stringify(jsonObject);
我尝试传递一个替换参数(stringify 上的第二个参数),但问题是该值已被处理.
I tried passing a replacer parameter (second parameter on stringify) but the problem is that the value has already been processed.
我也尝试在日期对象上使用 toString()
和 toUTCString()
,但这些也没有给我我想要的..
I also tried using toString()
and toUTCString()
on the date object, but these don't give me what I want either..
有人可以帮我吗?
推荐答案
最近我遇到了同样的问题.它是使用以下代码解决的:
Recently I have run into the same issue. And it was resolved using the following code:
x = new Date();
let hoursDiff = x.getHours() - x.getTimezoneOffset() / 60;
let minutesDiff = (x.getHours() - x.getTimezoneOffset()) % 60;
x.setHours(hoursDiff);
x.setMinutes(minutesDiff);
这篇关于由于 UTC,JSON Stringify 更改日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!