Logo

JSON中时间对象的输出格式是怎么定义的?

avatar rain 20 Apr 2015

我们做API开发时,响应格式多数会输出JSON格式,而其中日期时间对象的输出类似 “2012-04-23T18:25:43.511Z”,这个是根据什么标准吗?

JSON格式是有一套标准规范的,具体看 http://json.org, 但没有明确规范日期时间对象的输出格式,不过Javascript ECMA 规范里有实现。

根据按ECMA 5中的 Date.prototype.toJSON 的实现标准,输出结果是遵从ISO 8601标准,具体看定义可看ecma规范文档:

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

15.9.1.15 Date Time String Format

ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ

refs:

  • http://json.org/

  • http://stackoverflow.com/questions/10286204/the-right-json-date-format/15952652#15952652

JSON itself does not specify how dates should be represented, but JavaScript does.

You should use the format emitted by Date’s toJSON method:

2012-04-23T18:25:43.511Z

Here’s why:

It’s human readable but also succinct

It sorts correctly

It includes fractional seconds, which can help re-establish chronology

It conforms to ISO 8601

ISO 8601 has been well-established internationally for more than a decade

ISO 8601 is endorsed by W3C, RFC3339, and XKCD

That being said, every date library ever written can understand “milliseconds >since 1970”. So for easy portability, ThiefMaster is right.

http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf

ECMA-404 The JSON Data Interchange Standard.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON

Date.prototype.toJSON()

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.5.44

15.9.5.44 Date.prototype.toJSON ( key )
Let toISO be the result of calling the [[Get]] internal method of O with argument “toISOString”.

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.5.43

15.9.5.43 Date.prototype.toISOString ( )
This function returns a String value represent the instance in time represented by this Date object. The format of the String is the Date Time string format defined in 15.9.1.15.

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

15.9.1.15 Date Time String Format
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ

http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html#method-i-as_json

Coerces time to a string for JSON encoding. The default format is ISO 8601. You can get %Y/%m/%d %H:%M:%S +offset style by setting ActiveSupport::JSON::Encoding.use_standard_json_time_format to false.