I have a date object that's created by the user, with the timezone filled in by the browser, like so:

var date = new Date(2011, 05, 07, 04, 0, 0);
> Tue Jun 07 2011 04:00:00 GMT+1000 (E. Australia Standard Time)

不过,当我把它串起来时,时区就消失了

JSON.stringify(date);
> "2011-06-06T18:00:00.000Z"

在保留浏览器时区的同时获得ISO8601字符串的最佳方式是使用oment.js并使用moment.format(),但当然,如果我通过内部使用JSON.stringify的方式(在本例中为AngularJS)序列化整个命令,那么这将不起作用.

var command = { time: date, contents: 'foo' };
$http.post('/Notes/Add', command);

For completeness, my domain does need both the local time and the offset.

推荐答案

Assuming you have some kind of object that contains a Date:

var o = { d : new Date() };

您可以覆盖Date原型的toJSON功能.在这里,我用片刻.js从日期创建一个moment对象,然后使用moment的format函数(不带参数),该函数将发出包含偏移量的ISO8601扩展格式.

Date.prototype.toJSON = function(){ return moment(this).format(); }

Now when you serialize the object, it will use the date format you asked for:

var json = JSON.stringify(o);  //  '{"d":"2015-06-28T13:51:13-07:00"}'

Of course, that will affect all Date objects. If you want to change the behavior of only the specific date object, you can override just that particular object's toJSON function, like this:

o.d.toJSON = function(){ return moment(this).format(); }

Json相关问答推荐

写入JSON文件的流

我发现GoFr响应总是包含在数据字段中,如何返回自定义响应?

如何在改装Android中将ResponseBody转换为JSONObject

数据到jsonObject到数据到 struct 是可能的吗?

当并非所有子对象都有 Select 器字段时 Select

流导入错误:重新上传时不存在布局释放 UUID

如何从 JSON 中获取数据并通过 vb6 在网格中显示

使用 Ansible 解析来自 Juniper 交换机的 JSON 输出

Microsoft GRAPH 查询使用端点 /deviceManagement/deviceHealthScripts 列出了一种不熟悉的检测脚本内容格式

字典和对象的模型创建问题

如何比较 JSON 文档并返回与 Jackson 或 Gson 的差异?

将 ES6 类对象序列化为 JSON

在 Bash 中访问 JSON 对象 - 关联数组/列表/另一个模型

使用 gson 反序列化对象的特定 JSON 字段

如何在 json 编码字符串内的子数组数据周围添加方括号?

如何访问 JSON 对象数组的第一个元素?

在 HTML 数据属性上添加 JSON 是不是很糟糕?

严重:找不到媒体类型 = 应用程序/json、类型 = 类 com.jersey.jaxb.Todo、通用类型 = 类 com.jersey.jaxb.Todo 的 MessageBodyWriter

杰克逊在通用列表中读取 json

SCRIPT5009:JSON未定义