mar*_*ith 93 javascript datetime json utc
我在JavaScript中的日期对象始终由UTC + 2表示,因为我所处的位置.就像这样
Mon Sep 28 10:00:00 UTC+0200 2009
Run Code Online (Sandbox Code Playgroud)
问题在于JSON.stringify将上述日期转换为
2009-09-28T08:00:00Z (notice 2 hours missing i.e. 8 instead of 10)
Run Code Online (Sandbox Code Playgroud)
我需要的是获得荣誉的日期和时间,但事实并非如此,因此它应该是
2009-09-28T10:00:00Z (this is how it should be)
Run Code Online (Sandbox Code Playgroud)
基本上我用这个:
var jsonData = JSON.stringify(jsonObject);
Run Code Online (Sandbox Code Playgroud)
我尝试传递一个replacer参数(stringify上的第二个参数),但问题是该值已经被处理.
我也试过使用toString()和toUTCString()日期对象,但这些并没有给我我想要的东西..
谁能帮我?
Ana*_*liy 62
最近我遇到了同样的问题.它使用以下代码解决:
x = new Date();
let hoursDiff = x.getHours() - x.getTimezoneOffset() / 60;
let minutesDiff = (x.getHours() - x.getTimezoneOffset()) % 60;
x.setHours(hoursDiff);
x.setMinutes(minutesDiff);
Run Code Online (Sandbox Code Playgroud)
oll*_*iej 37
JSON使用Date.prototype.toISOString不代表本地时间的函数 - 它表示未修改的UTC时间 - 如果查看日期输出,您可以看到您处于UTC + 2小时,这就是JSON字符串更改两小时的原因,但如果这允许在多个时区正确表示相同的时间.
Loc*_*uis 15
只是为了记录,请记住"2009-09-28T08:00:00Z"中的最后一个"Z"表示时间确实是UTC.
有关详细信息,请参见http://en.wikipedia.org/wiki/ISO_8601.
ali*_*efi 13
date.toJSON() 将 UTC-Date 打印为格式化的字符串(因此在将其转换为 JSON 格式时添加偏移量)。
date = new Date();
new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON();
Run Code Online (Sandbox Code Playgroud)
强制JSON.stringify忽略时区的开箱即用解决方案:
// Before: JSON.stringify apply timezone offset
const date = new Date();
let string = JSON.stringify(date);
console.log(string);
// After: JSON.stringify keeps date as-is!
Date.prototype.toJSON = function(){
const hoursDiff = this.getHours() - this.getTimezoneOffset() / 60;
this.setHours(hoursDiff);
return this.toISOString();
};
string = JSON.stringify(date);
console.log(string);Run Code Online (Sandbox Code Playgroud)
使用 moment + moment-timezone 库:
const date = new Date();
let string = JSON.stringify(date);
console.log(string);
Date.prototype.toJSON = function(){
return moment(this).format("YYYY-MM-DDTHH:mm:ss:ms");;
};
string = JSON.stringify(date);
console.log(string);Run Code Online (Sandbox Code Playgroud)
<html>
<header>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>
</header>
</html>Run Code Online (Sandbox Code Playgroud)
这是另一个答案(我个人认为这更合适)
var currentDate = new Date();
currentDate = JSON.stringify(currentDate);
// Now currentDate is in a different format... oh gosh what do we do...
currentDate = new Date(JSON.parse(currentDate));
// Now currentDate is back to its original form :)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
93763 次 |
| 最近记录: |