1505

I've seen so many different standards for the JSON date format:

"\"\\/Date(1335205592410)\\/\""         .NET JavaScriptSerializer
"\"\\/Date(1335205592410-0500)\\/\""    .NET DataContractJsonSerializer
"2012-04-23T18:25:43.511Z"              JavaScript built-in JSON object
"2012-04-21T18:25:43-05:00"             ISO 8601

Which one is the right one? Or best? Is there any sort of standard on this?

leonheess
  • 16,068
  • 14
  • 77
  • 112
Kamyar Nazeri
  • 25,786
  • 15
  • 50
  • 87
  • 103
    There is no date format in JSON, there's only strings a de-/serializer decides to map to date values. –  Apr 23 '12 at 18:34
  • 13
    `strings`, `numbers`, `true`, `false`, `null`, `objects` and `arrays` – Russ Cam Apr 23 '12 at 18:44
  • 17
    However, *JavaScript built-in JSON object* and *ISO8601* contains all the information to be understand by human and computer and does not relies on the beginning of the computer era (1970-1-1). – poussma Jan 23 '13 at 13:58
  • 1
    https://stackoverflow.com/questions/58847869/utc-vs-iso-format-for-time A good reference and nice to read. – Abhishek Gautam Nov 25 '21 at 20:51
  • [json](https://fe-tool.com/en-us/formatter/json) supports number and string for `date`. – cwtuan Jan 10 '23 at 13:13

16 Answers16

2416

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:

  1. It's human readable but also succinct

  2. It sorts correctly

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

  4. It conforms to ISO 8601

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

  6. 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.

Community
  • 1
  • 1
funroll
  • 35,925
  • 7
  • 54
  • 59
  • 46
    This is also the preferred representations according to [ECMA](http://es5.github.io/#x15.12.3): `JSON.stringify({'now': new Date()}) "{"now":"2013-10-21T13:28:06.419Z"}"` – Steven Oct 21 '13 at 13:28
  • 18
    I would add another important reason to the list: it's locale-independent. If you had a date like 02-03-2014 you'd need additional information to know if it refers to the 3rd of Feb or the 2nd of March. It depends on whether US-format or other format is used. – Juanal Jul 02 '14 at 07:41
  • 2
    Take into account that some browsers don't parse ISO8601, like safari for example. – ajorquera Nov 05 '14 at 11:23
  • 135
    upvote for mentioning and linking xkcd :D @ajorquera I usually use momentjs for this. I've also seen issues with IE in this regard – fholzer Apr 29 '15 at 16:12
  • 1
    I guess a better aproach is to add the time offset. The very simple reason is that you know exactly the date where, maybe an event, was created from _your_ location but you don't know the date where the event took place. If happens to be that you don't know where this event was taken, then you can't take enough information from the event regarding the location it was generated. – Sebastian Jun 04 '15 at 03:31
  • 68
    Regarding the second point, it does not sort correctly after the year 10000. We do have almost 8000 years to come up with a new format though, so it's probably not an issue. – Erfa Aug 19 '15 at 14:29
  • Sebastian is right regarding the date issue, but it's even simpler to use the date-only ISO format (which you can see in the xkcd strip). Both still have to replace javascript's standard JSON serialization in any case. – Pif Oct 26 '15 at 09:52
  • 2
    How is "it sorts correctly" relevant when serializing a date to JSON? – Marten Jan 01 '16 at 15:46
  • 1
    Also Date.toJSON() doesn't support all-day dates nor floating times nor time zones. – Marten Jan 01 '16 at 15:50
  • 2
    The trouble with the number of seconds since 1970 is that it does not include a timezone. You should *not* use that. Ever. A date without a timezone is always localized, be aware of that! – Gerard van Helden Jan 27 '16 at 16:40
  • 5
    Unfortunately, `JSON.parse()` will not reproduce a date object, but keep it as string: `JSON.parse(JSON.stringify({'now': new Date()}))` gives `{now: "2016-03-30T15:49:18.369Z"}`. – Alexander Klimetschek Mar 30 '16 at 15:49
  • 10
    Actually, @Erfa, since `-` comes before digits in `ASCII`, it will sort just fine until the year 100,000. ;P – Ky - May 02 '16 at 18:23
  • 3
    The great thing about ISO8601 is that it includes so many formats to choose from! – aij Sep 21 '16 at 17:35
  • 9
    @gerard-van-helden Contrary to your statement, a unix timestamp is well defined and is always UTC. – lkraider Nov 10 '16 at 15:48
  • @Marten - Sorting is relevant because when dates are represented as ISO strings, lexical and time-wise sort collapse to the same operation. Saves CPU and simplifies code since lexical sort is default for plain old `.sort()`. – greim Apr 25 '17 at 22:39
  • 1
    @lkraider This is not always true. A unix timestamp doesn't carry any information about timezone, so is **good practice** to convert date to UTC before getting the timestamp, but it's not always honoured. One should not rely on the programming language to make this conversion. – Dinei May 10 '17 at 15:56
  • 4
    @DineiRockenbach the Unix Time is "the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds" - so it doesn't match UTC on leap seconds, but otherwise it is always UTC. Now, conversions between different representations is entirely on you to get right. – lkraider May 10 '17 at 23:26
  • 5
    XKCD's pushing of ISO 8601 format is especially funny that the hover tip says _ISO 8601 was published on 06/05/88 and most recently amended on 12/01/04_ to highlight the confusion. – AlwaysLearning Sep 29 '17 at 00:25
  • 2
    OP's question is about DATE, not about DATE and TIME. How best to represent just date without time? For example, `birth_date`? – yerzhan7 Apr 19 '18 at 07:14
  • 1
    javascript `Date.parse()` also takes ISO8601 as its default parameter format https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Parameters – Leonard AB May 10 '19 at 07:32
  • *(Just my irrelevant and unnecessary 2 cents.)* I think `-` was a terrible choice and `2020M09D03` or `2020x09y03` would have been much better :) – tymtam Sep 03 '20 at 05:33
  • what about https://tools.ietf.org/html/rfc5322#section-3.6.1 which is the standard for the HTTP Date header, and is reference by https://tools.ietf.org/html/rfc7231#section-7.1.1.2? RFC5322 does not even mention RFC3339 or ISO8601 yet it is the standard for _header_ in every response that carries a JSON object. What gives? – Rhubarb Jan 21 '21 at 15:25
  • This format REALLY needs a name. It's often incorrectly referred to as ISO8601 (which it conforms to), but it's simpler and guarantees the tasty 'it sorts correctly' (can be compared as string) property. How about 'Zulu millis'? – jedwidz Mar 04 '21 at 11:31
  • Since 2015 [I-JSON specifies ISO8601](https://tools.ietf.org/html/rfc7493#section-4.3) as the standard date format. The JSON link points to a historical site, not the JSON specification itself. There are differences, especially around whitespace – Panagiotis Kanavos Apr 22 '21 at 06:53
  • 2
    For "more than a decade" read "half a century". The standard we know as ISO 8601 was first published as ISO recommendation 2014 back in 1971. – Michael Kay May 17 '21 at 21:45
  • Technically it's "milliseconds from Jan 1 1970, 0 hours, UTC" – JoelFan Jun 19 '21 at 18:53
  • 3
    Bonus points for referencing XKCD in your answer. – 6006604 Sep 19 '22 at 20:13
  • @Pif if you are working on a problem like doing a simulation of events beyond the year 9999 then the sorting would become an issue... :D – wk t May 24 '23 at 06:47
155

JSON does not know anything about dates. What .NET does is a non-standard hack/extension.

I would use a format that can be easily converted to a Date object in JavaScript, i.e. one that can be passed to new Date(...). The easiest and probably most portable format is the timestamp containing milliseconds since 1970.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 1
    Does the JavaScript built-in JSON.stringify format is the most accepted one? And why?! why isn't any standard on this? and yet all browsers behave the same when stringify Date object?! – Kamyar Nazeri Apr 23 '12 at 18:39
  • 2
    Ugh, I'd expect an error... But at least firefox does stringify it... well, it's not part of the JSON standard so I wouldn't feed a Date object to a JSON serializer - it might not work in all browsers. Apparently it's a common idea for JSON serializers to use a `toJSON()` function if it exists on an unknown object. At least Firefox does that for Date objects and Date objects do have such a method. – ThiefMaster Apr 23 '12 at 18:40
  • 3
    http://stackoverflow.com/questions/10286385/why-does-json-stringify-accept-date-objects - let's see if someone knows why FF behaves like that. – ThiefMaster Apr 23 '12 at 18:47
  • 23
    If you go this route, make sure you don't need to deal with dates earlier than 1970! – Ben Dolman May 09 '13 at 21:14
  • 2
    There are applications/libraries that support negative timestamps. – ThiefMaster May 10 '13 at 06:18
  • 16
    As @BenDolman said, this "solution" doesn't deal appropriately with dates prior to Jan 1st, 1970 (Epoch). Also, there is a reason ISO8601 exists in the first place. Here on Earth we have things called "time zones." Where is that in milliseconds? JSON may not have a standard for dates, but dates exist outside of JSON, and there _is_ a standard for that. funroll's answer is the correct one (see also: http://xkcd.com/1179/). – JoeLinux Nov 14 '13 at 20:19
  • 1
    It's not a .NET *hack*, back then nobody had tried to define a date format standard. When Microsoft created Ajax they had to pass dates so they tried to use an escaped and tagged unix timestamp (like the other libraries you mentioned) that wouldn't be confused with text or integers. This isn't used in .NET anymore, everyone uses Json.NET or other serializers that support the ISO format – Panagiotis Kanavos Dec 19 '14 at 12:27
  • 7
    It is maybe also worth mentioning that (milli)seconds from 1970 isn't predictable for dates in the future because we have [leap seconds](https://en.wikipedia.org/wiki/Leap_second). So I wouldn't use if for inter-process communication and data storage. It is however nice to use internally in a program since it can be stored in a single integer which gives you some performance benefits. – Brodie Garnet Nov 03 '15 at 13:56
  • The biggest trouble imho with timestamps is that they do not include a timezone. This can be troublesome. (though most libraries assume UTC, not all do and that makes it very confusing). date representations therefore should always include a timezone, and a simple `uint` representation can not. – Gerard van Helden Jan 27 '16 at 16:42
  • 9
    The Unix timestamp is always UTC, you convert from your local timezone before generating the timestamp, and back again to the local timezone on display, there is no ambiguity there. – lkraider Nov 10 '16 at 15:51
  • 9
    Every one of these comments saying that pre-1970s dates or future dates can't be represented is misunderstanding epoch time. All time is relative, and the date string will _really_ break down once you get at/below year 1. Whatever the source clock for your time, it's almost certainly based on a representation from epoch-time anyway, so you're not making it more accurate by avoiding epoch time. – Josh from Qaribou Nov 20 '16 at 15:58
  • 1
    @JoshfromQaribou ISO 8601 does have representations at and below [year zero](https://en.wikipedia.org/wiki/Year_zero). In general though anything below 1583 apparently will likely break most parsers though. So you are basically right in that the epoch fear is sort of unwarranted. – Adam Gent May 10 '17 at 16:07
  • 1
    Dates before 1970 can be handled by a negative numeric timestamp. When rounding, one needs to take care to round towards negative infinity instead of zero. Windows, Unix, and Javascript APIs that return date/time as a numeric timestamp ignore leap seconds (i.e. every day has 86400 seconds), so the argument about their predictability does not apply if the communications protocol dictates that all days have 86400 seconds. If the application/protocol *does* need to deal with leap seconds, then a numeric timestamp can't be used for the reasons already stated in the above comments. – Emile Cormier Feb 23 '21 at 22:56
  • @BrodieGarnet Just to reiterate Emile's point, unix/epoch time has 86400 seconds a day so remain accurate in the future. Leap seconds are addressed on a host by smearing the final second of the day into 86400. – Matt Jan 03 '23 at 07:19
65

There is no right format; The JSON specification does not specify a format for exchanging dates which is why there are so many different ways to do it.

The best format is arguably a date represented in ISO 8601 format (see Wikipedia); it is a well known and widely used format and can be handled across many different languages, making it very well suited for interoperability. If you have control over the generated json, for example, you provide data to other systems in json format, choosing 8601 as the date interchange format is a good choice.

If you do not have control over the generated json, for example, you are the consumer of json from several different existing systems, the best way of handling this is to have a date parsing utility function to handle the different formats expected.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
  • 3
    @mlissner but that's an *opinion* on which one is best. ISO-8601 is a standard, but it's not *the standard for JSON* (even though I'd be inclined to use it); for example, Microsoft decided not to use it (http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_sidebarb). The best practice is to stick with one (sensible) convention , whatever that is. As I stated in the answer, the best way of handling this is to define a date parsing utility function that can handle the expected formats. If you integrate with systems that use different formats, the function should handle each case. – Russ Cam Apr 30 '13 at 08:07
  • 2
    @RussCam, we can go back and forth, but if somebody is asking the best way to encode dates in JSON, they're asking how to format dates when they make JSON (and the answer is generally ISO-8601). You're answering the opposite question: how to consume JSON dates once they're already made (though your advice is sound). – mlissner Apr 30 '13 at 20:32
  • 1
    The JSON schema specification actually says that dates that are verified by a schema must be in 8601 format. – gnasher729 Jan 16 '15 at 16:20
  • 3
    @gnasher729 do you have a link? – Russ Cam Jan 16 '15 at 21:56
  • 1
    @vallismortis - That is a draft specification for defining a schema for a given json structure exchanged between parties, not the format for dates in the json specification. I'm going to revise my answer as based on the comments, it doesn't appear I've made it clear enough – Russ Cam Jun 27 '15 at 00:32
  • Minor nit pick, but I'm not sure I'd say "Microsoft decided not to use it," it's more that *.Net* decided not to use it. I'm using a complete Microsoft toolchain with Typescript as well as C++ and JSON and happily consuming ISO-8601 formats. YMMV. – J. Gwinner Aug 26 '21 at 03:48
37

When in doubt simply go to the javascript web console of a modern browser by pressing F12 (Ctrl+Shift+K in Firefox) and write the following:

new Date().toISOString()

Will output:

"2019-07-04T13:33:03.969Z"

Ta-da!!

Shayan Ahmad
  • 952
  • 8
  • 17
  • Although that is a _reasonable_ format, this answer doesn't say anything about why it's a sensible or useful one for JSON. Why is JS relevant? Why is `toISOString` relevant? – IMSoP Jul 26 '22 at 08:43
  • @IMSoP perhaps because an ISO Standard is way better than a date to string conversion – Lepy Aug 16 '22 at 11:48
  • @Lepy That sentence doesn't really make sense - it's still just being converted to string, just choosing a particular format. And as I already said, it's a _reasonable_ format, but the answer doesn't say anything about why it should be used; and the question is not about JS, it's about JSON. I'm commenting on the _quality of the answer_, not on whether I agree with it. – IMSoP Aug 16 '22 at 11:56
  • @IMSoP, I would encourage you to learn about [how ISO 8601 date format](https://www.w3docs.com/snippets/javascript/the-right-json-date-format.html) is an excellent usage when transporting date in JSON. The key in understanding the answer I provided boils down to the [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) part that when used yields an ISO 8601 format. – Shayan Ahmad Aug 19 '22 at 01:18
  • 9
    So, once again, my comment is not about whether this is a good format, it's about **what is missing from the text of this answer**. If someone didn't know anything about this format, and read your answer, they *still* wouldn't know anything about this format; they wouldn't even know its name. My questions were prompts for information that should be edited into the answer. – IMSoP Aug 19 '22 at 06:41
  • I see your point @IMSoP, I shall add some information that would indicate what makes the result of the JSON valid. – Shayan Ahmad Aug 01 '23 at 13:38
33

From RFC 7493 (The I-JSON Message Format ):

I-JSON stands for either Internet JSON or Interoperable JSON, depending on who you ask.

Protocols often contain data items that are designed to contain timestamps or time durations. It is RECOMMENDED that all such data items be expressed as string values in ISO 8601 format, as specified in RFC 3339, with the additional restrictions that uppercase rather than lowercase letters be used, that the timezone be included not defaulted, and that optional trailing seconds be included even when their value is "00". It is also RECOMMENDED that all data items containing time durations conform to the "duration" production in Appendix A of RFC 3339, with the same additional restrictions.

Community
  • 1
  • 1
Bryan Larsen
  • 9,468
  • 8
  • 56
  • 46
  • 3
    This is also the format produced by `Date().toISOString()` and `Date().toJSON()`, with the limitation that `Date` doesn't track a timezone value, and hence always emits the timestamps in the UTC (`Z`) timezone. The value can be parsed using `new Date("...")` and `Date.parseDate`. – Søren Løvborg Sep 21 '15 at 09:06
22

Just for reference I've seen this format used:

Date.UTC(2017,2,22)

It works with JSONP which is supported by the $.getJSON() function. Not sure I would go so far as to recommend this approach... just throwing it out there as a possibility because people are doing it this way.

FWIW: Never use seconds since epoch in a communication protocol, nor milliseconds since epoch, because these are fraught with danger thanks to the randomized implementation of leap seconds (you have no idea whether sender and receiver both properly implement UTC leap seconds).

Kind of a pet hate, but many people believe that UTC is just the new name for GMT -- wrong! If your system does not implement leap seconds then you are using GMT (often called UTC despite being incorrect). If you do fully implement leap seconds you really are using UTC. Future leap seconds cannot be known; they get published by the IERS as necessary and require constant updates. If you are running a system that attempts to implement leap seconds but contains and out-of-date reference table (more common than you might think) then you have neither GMT, nor UTC, you have a wonky system pretending to be UTC.

These date counters are only compatible when expressed in a broken down format (y, m, d, etc). They are NEVER compatible in an epoch format. Keep that in mind.

Tel
  • 404
  • 4
  • 2
20

"2014-01-01T23:28:56.782Z"

The date is represented in a standard and sortable format that represents a UTC time (indicated by the Z). ISO 8601 also supports time zones by replacing the Z with + or – value for the timezone offset:

"2014-02-01T09:28:56.321-10:00"

There are other variations of the timezone encoding in the ISO 8601 spec, but the –10:00 format is the only TZ format that current JSON parsers support. In general it’s best to use the UTC based format (Z) unless you have a specific need for figuring out the time zone in which the date was produced (possible only in server side generation).

NB:

    var date = new Date();
    console.log(date); // Wed Jan 01 2014 13:28:56 GMT- 
    1000 (Hawaiian Standard Time) 
        
    var json = JSON.stringify(date);
    console.log(json);  // "2014-01-01T23:28:56.782Z"

To tell you that's the preferred way even though JavaScript doesn't have a standard format for it

// JSON encoded date
var json = "\"2014-01-01T23:28:56.782Z\"";

var dateStr = JSON.parse(json);  
console.log(dateStr); // 2014-01-01T23:28:56.782Z
Aryan
  • 3,338
  • 4
  • 18
  • 43
Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67
11

JSON itself has no date format, it does not care how anyone stores dates. However, since this question is tagged with javascript, I assume you want to know how to store javascript dates in JSON. You can just pass in a date to the JSON.stringify method, and it will use Date.prototype.toJSON by default, which in turns uses Date.prototype.toISOString (MDN on Date.toJSON):

const json = JSON.stringify(new Date());
const parsed = JSON.parse(json); //2015-10-26T07:46:36.611Z
const date = new Date(parsed); // Back to date object

I also found it useful to use the reviver parameter of JSON.parse (MDN on JSON.parse) to automatically convert ISO strings back to javascript dates whenever I read JSON strings.

const isoDatePattern = new RegExp(/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/);

const obj = {
 a: 'foo',
 b: new Date(1500000000000) // Fri Jul 14 2017, etc...
}
const json = JSON.stringify(obj);

// Convert back, use reviver function:
const parsed = JSON.parse(json, (key, value) => {
    if (typeof value === 'string' &&  value.match(isoDatePattern)){
        return new Date(value); // isostring, so cast to js date
    }
    return value; // leave any other value as-is
});
console.log(parsed.b); // // Fri Jul 14 2017, etc...
Justus Romijn
  • 15,699
  • 5
  • 51
  • 63
6

The prefered way is using 2018-04-23T18:25:43.511Z...

The picture below shows why this is the prefered way:

JSON Date

So as you see Date has a native Method toJSON, which return in this format and can be easily converted to Date again...

Alireza
  • 100,211
  • 27
  • 269
  • 172
  • 2
    Correct! The JSON Data Interchange Syntax does not specify the standard: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf but in practice, ISO 8601 compatible formats are more desirable across platforms including JavaScript runtime. – Kamyar Nazeri Jan 31 '19 at 14:45
  • The picture just shows that this is how JS has chosen to implement it, and the question already said as much. That doesn't have any bearing at all on what other languages might do, or what might be good practice - there's plenty of things that JS has chosen to implement which other languages would consider _terrible_ practice. – IMSoP Jul 26 '22 at 08:47
3

In Sharepoint 2013, getting data in JSON there is no format to convert date into date only format, because in that date should be in ISO format

yourDate.substring(0,10)

This may be helpful for you

irundaia
  • 1,720
  • 17
  • 25
raghava arr
  • 183
  • 1
  • 14
3

I believe that the best format for universal interoperability is not the ISO-8601 string, but rather the format used by EJSON:

{ "myDateField": { "$date" : <ms-since-epoch> } }

As described here: https://docs.meteor.com/api/ejson.html

Benefits

  1. Parsing performance: If you store dates as ISO-8601 strings, this is great if you are expecting a date value under that particular field, but if you have a system which must determine value types without context, you're parsing every string for a date format.
  2. No Need for Date Validation: You need not worry about validation and verification of the date. Even if a string matches ISO-8601 format, it may not be a real date; this can never happen with an EJSON date.
  3. Unambiguous Type Declaration: as far as generic data systems go, if you wanted to store an ISO string as a string in one case, and a real system date in another, generic systems adopting the ISO-8601 string format will not allow this, mechanically (without escape tricks or similar awful solutions).

Conclusion

I understand that a human-readable format (ISO-8601 string) is helpful and more convenient for 80% of use cases, and indeed no-one should ever be told not to store their dates as ISO-8601 strings if that's what their applications understand, but for a universally accepted transport format which should guarantee certain values to for sure be dates, how can we allow for ambiguity and need for so much validation?

Ciabaros
  • 1,984
  • 13
  • 15
  • 1
    See this answer earlier in the thread for why milliseconds since epoch has caveats such as incorrect computation of leap seconds etc: https://stackoverflow.com/a/42480073/190476 – Sudhanshu Mishra Nov 01 '19 at 05:19
  • @SudhanshuMishra The caveats you reference are general gotchas for extremely academic concerns of unix timestamps, mostly related to timestamp generation. This is even less of a concern with millisecond resolution. As was called out in another comment, most computer dates are internally represented as a unix timestamps, even if they are exposed and formatted otherwise. Nonetheless, there is nothing wrong with millisecond representation of any given date+time, especially when compared with other approaches, which can easily be affected by the same nano-impact caveats under the hood. – Ciabaros Nov 01 '19 at 20:10
  • Just to add regarding concerns of "out of range" dates for unix timestamps: those are system storage issues, to be addressed in a much wider context than the transport format. For instance, this format does not need to be limited to integers that fit into 32 bits, nor does it need to be strictly positive numbers, but nobody is going to solve the "year 2038 problem" by dropping timestamps on a system/architecture level; they just need to be expanded (e.g. to 64-bit or beyond), and this does not affect this proposed transport format. – Ciabaros Nov 01 '19 at 20:39
  • Too late. That might have been a good format to use for JSON, but now most systems in the wild use ISO8601 or straight time since epoch, anything else is an interoperability headache. EJSON reminds me of this: https://xkcd.com/927/ It provide solutions for working with JSON in JS, but there is an awful lot of JSON that isn't processed using JS. – Yaytay Apr 07 '22 at 06:33
  • @Yaytay the number in EJSON is "straight time since epoch", in milliseconds. That's what a timestamp usually is. – Ciabaros Jan 03 '23 at 01:05
0

There is no official date format in JSON. The but best solution is to use the ISO 8601 format, describing a date as a string like "2023-08-17T08:20:28.438Z".

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Jos de Jong
  • 6,602
  • 3
  • 38
  • 58
-3

it is work for me with parse Server

{
    "ContractID": "203-17-DC0101-00003-10011",
    "Supplier":"Sample Co., Ltd",
    "Value":12345.80,
    "Curency":"USD",
    "StartDate": {
                "__type": "Date",
                "iso": "2017-08-22T06:11:00.000Z"
            }
}
Rosdi Kasim
  • 24,267
  • 23
  • 130
  • 154
Kemal Karadag
  • 446
  • 4
  • 4
-8

There is only one correct answer to this and most systems get it wrong. Number of milliseconds since epoch, aka a 64 bit integer. Time Zone is a UI concern and has no business in the app layer or db layer. Why does your db care what time zone something is, when you know it's going to store it as a 64 bit integer then do the transformation calculations.

Strip out the extraneous bits and just treat dates as numbers up to the UI. You can use simple arithmetic operators to do queries and logic.

Chad Wilson
  • 121
  • 3
  • Comments have been [moved to chat](http://chat.stackoverflow.com/rooms/114055/discussion-on-answer-by-chad-wilson-the-right-json-date-format). – Jon Clements Jun 07 '16 at 17:13
  • 7
    Now you have 2 problems: Which epoch should you choose, and which milliseconds should you count? Probably the most common choice is Unix time (1970-01-01T00:00:00 UTC and SI milliseconds except for those which fall within a leap second), but of course that makes future times undefined. – aij Sep 21 '16 at 18:51
  • 4
    So how do you represent microseconds? RFC3339 works fine with any precision, you'll have a reader that parses the timezone and gives you the right time stamp, and it's additional information. Calendar apps usually care about time zones. – gnasher729 Nov 04 '16 at 17:05
  • I loved using milliseconds from the unix epoch, until I dealt with a poorly documented system which was using milliseconds from the unix epoch in easter time! That's not fun to debug. At least with a timestamp you have the option to describe awkward data sets like this by specifying a time zone. – Timothy Gonzalez Nov 08 '16 at 17:22
  • 14
    Timezone is not a UI concern, unless you don't mind missing your next flight. Flights are posted in local time and follow specific rules for DST changes. Losing the offset means losing important business information – Panagiotis Kanavos Dec 05 '16 at 12:00
  • 3
    Some further counterarguments include the ability to represent times before 1970 (assuming that particular epoch), and JSONs tendency to be somewhat human-readable. – Timo Dec 13 '16 at 16:36
  • Downvote reason: Answer is wrong and you're digging yourself into a huge hole if you try and implement your own epoch to time/date converter from scratch. You'd have to be insane to reinvent the wheel when loads of stable date time libraries exist. – NickG Apr 18 '19 at 08:23
  • 2
    Regarding the timezone comment pitchforks: while I agree that it's dangerous to say which layer's concern it is (UI, Business Logic as Data), as that is application specific -- a universal approach to STORE datetimes should NOT include the timezone as you can always derive any timezone specific variation of the datetime, through standard well understood means. I feel that any arguments for storing time zones universally baked into dates are misguided in trying to include LOCATION into the datetime, which should rather be stored as separate independent data. – Ciabaros Nov 01 '19 at 20:29
  • @Ciabaros Unlike you, I consider the time zone information itself valuable information. A very simple example: A database contains day, hour and minute of my birth in UTC. If you want to know my birthday, you need the time zone! If you send an email at 2am from Los Angeles or 11am London, that may be the same time in UTC, but the time zone is important. – gnasher729 Jan 01 '23 at 22:19
  • @gnasher729 if you are reading the date from a source that used a timezone, then of course you need to know that, but timestamps (for ex) don't have that problem, since they are absolute. I'm not saying timezones are bad or that they need to be ignored when already encoded - just that they are not needed to store PURE datetime data. – Ciabaros Jan 03 '23 at 01:01
-12

The following code has worked for me. This code will print date in DD-MM-YYYY format.

DateValue=DateValue.substring(6,8)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(0,4);

else, you can also use:

DateValue=DateValue.substring(0,4)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(6,8);
Phil3992
  • 1,059
  • 6
  • 21
  • 45
-21

I think that really depends on the use case. In many cases it might be more beneficial to use a proper object model (instead of rendering the date to a string), like so:

{
"person" :
      {
 "name" : {
   "first": "Tom",
   "middle": "M",
  ...
}
 "dob" :  {
         "year": 2012,
         "month": 4,
         "day": 23,
         "hour": 18,
         "minute": 25,
         "second": 43,
         "timeZone": "America/New_York"
    }   
   }
}

Admittedly this is more verbose than RFC 3339 but:

  • it's human readable as well
  • it implements a proper object model (as in OOP, as far as JSON permits it)
  • it supports time zones (not just the UTC offset at the given date and time)
  • it can support smaller units like milliseconds, nanoseconds, ... or simply fractional seconds
  • it doesn't require a separate parsing step (to parse the date-time string), the JSON parser will do everything for you
  • easy creation with any date-time framework or implementation in any language
  • can easily be extended to support other calendar scales (Hebrew, Chinese, Islamic ...) and eras (AD, BC, ...)
  • it's year 10000 safe ;-) (RFC 3339 isn't)
  • supports all-day dates and floating times (Javascript's Date.toJSON() doesn't)

I don't think that correct sorting (as noted by funroll for RFC 3339) is a feature that's really needed when serializing a date to JSON. Also that's only true for date-times having the same time zone offset.

Mukus
  • 4,870
  • 2
  • 43
  • 56
Marten
  • 3,802
  • 1
  • 17
  • 26
  • 8
    I doubt anyone will be using json in the year 10000, or even that by that time the year 10000 will still be year 10000. But if both of those things are still true by then, the format can simply be expanded to contain a 3 digit century component. So I'd say people can safely stick with RFC 3339, at least until the year 9900 – memory of a dream Mar 09 '16 at 12:15
  • 7
    @Marten Two things. 1. You are never owed an explanation for downvotes, though I understand it can be helpful. 2. I did not downvote your answer, but I would guess that people don't like your answer because they think it is the wrong way to do this. That would qualify it as "Wrong information" since the question is looking for the best way to do something – Kevin Jun 29 '16 at 17:52
  • 10
    I did not downvote you, but I can certainly understand how "invent yet another poorly specified format" (which is basically what you're saying) would be seen as wrong or poorly researched. – aij Sep 22 '16 at 13:45
  • 1
    Not a good option as this is not a standard interchange format. – lkraider Nov 10 '16 at 16:15
  • Too poor answer. I think this is a bad option because don't use or implement a standar – Olaf Erlandsen Dec 27 '16 at 14:30
  • 1
    As others pointed out, there is no standard for dates in JSON. There is only RFC 3339, which is actually a timestamp format, not a date format. In particular it doesn't cover time zones, but that's important for future dates. Time zones change more often than you might think. – Marten Dec 28 '16 at 00:57
  • 1
    @Marten it does cover time zones - the 'Z' indicates the time zone is UTC. I'd downvote too, but at this point, there's no further need. – Phil Aug 07 '17 at 22:29
  • 3
    @Phil, UTC is not really a time zone (there is no place on earth which uses "UTC" as its official time zone), it's a [time standard](https://en.wikipedia.org/wiki/Coordinated_Universal_Time). Also time zone offsets are quite unpredictable. There is no way to say if in 2025 "12:00 Moscow time" is still "9:00 UTC" like it is today, it has been [changed a couple of times during the last 30 years](https://en.wikipedia.org/wiki/Moscow_Time#Past_usage). If you want to express a future local time you need true time zones. – Marten Aug 08 '17 at 07:45
  • 2
    May I just say: You are tenacious! Keeping an answer posted with a (current) score of -15, that has collected 23 downvotes! (I didn't downvote, BTW) – random_user_name Feb 08 '18 at 17:06
  • @Marten I edited and upvoted you. I can see why what you did could be useful. – Mukus Sep 06 '18 at 03:53
  • 2
    Good read for the downvoters on why storing UTC timestamps is not always the best choice: https://codeblog.jonskeet.uk/2019/03/27/storing-utc-is-not-a-silver-bullet/ – Marten Apr 05 '19 at 07:42