What is the right JSON date format?
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.
How do I format a Microsoft JSON date?
eval()
is not necessary. This will work fine:
var date = new Date(parseInt(jsonDate.substr(6)));
The substr()
function takes out the /Date(
part, and the parseInt()
function gets the integer and ignores the )/
at the end. The resulting number is passed into the Date
constructor.
I have intentionally left out the radix (the 2nd argument to parseInt
); see my comment below.
Also, I completely agree with Rory's comment: ISO-8601 dates are preferred over this old format - so this format generally shouldn't be used for new development.
For ISO-8601 formatted JSON dates, just pass the string into the Date
constructor:
var date = new Date(jsonDate); //no ugly parsing needed; full timezone support
Format JSON DateTime
You can convert your string into a Date
object and then format it like this:
let jsonString = "2019-02-03T06:48:07";
// You should set your own timezone and options.
console.log(new Date(jsonString).toLocaleString('en-US', {hour12: false}))
What is the best way to store a date/time in JSON?
I recommend to use ISO 8601 dates. Especially this format
2014-03-12T13:37:27+00:00
is portable across many programming languages.
Edit:
JSON only knows these types:
string
number
object
array
true
false
null
Dates and datetimes are best stored as strings in a format that is widely used.
ASP.NET MVC JsonResult Date Format
Just to expand on casperOne's answer.
The JSON spec does not account for Date values. MS had to make a call, and the path they chose was to exploit a little trick in the javascript representation of strings: the string literal "/" is the same as "\/", and a string literal will never get serialized to "\/" (even "\/" must be mapped to "\\/").
See http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_topic2 for a better explanation (scroll down to "From JavaScript Literals to JSON")
One of the sore points of JSON is the
lack of a date/time literal. Many
people are surprised and disappointed
to learn this when they first
encounter JSON. The simple explanation
(consoling or not) for the absence of
a date/time literal is that JavaScript
never had one either: The support for
date and time values in JavaScript is
entirely provided through the Date
object. Most applications using JSON
as a data format, therefore, generally
tend to use either a string or a
number to express date and time
values. If a string is used, you can
generally expect it to be in the ISO
8601 format. If a number is used,
instead, then the value is usually
taken to mean the number of
milliseconds in Universal Coordinated
Time (UTC) since epoch, where epoch is
defined as midnight January 1, 1970
(UTC). Again, this is a mere
convention and not part of the JSON
standard. If you are exchanging data
with another application, you will
need to check its documentation to see
how it encodes date and time values
within a JSON literal. For example,
Microsoft's ASP.NET AJAX uses neither
of the described conventions. Rather,
it encodes .NET DateTime values as a
JSON string, where the content of the
string is /Date(ticks)/ and where
ticks represents milliseconds since
epoch (UTC). So November 29, 1989,
4:55:30 AM, in UTC is encoded as
"\/Date(628318530718)\/".
A solution would be to just parse it out:
value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));
However I've heard that there is a setting somewhere to get the serializer to output DateTime
objects with the new Date(xxx)
syntax. I'll try to dig that out.
The second parameter of JSON.parse()
accepts a reviver
function where prescribes how the value originally produced by, before being returned.
Here is an example for date:
var parsed = JSON.parse(data, function(key, value) {
if (typeof value === 'string') {
var d = /\/Date\((\d*)\)\//.exec(value);
return (d) ? new Date(+d[1]) : value;
}
return value;
});
See the docs of JSON.parse()
Date format Mapping to JSON Jackson
What is the formatting I need to use to carry out conversion with Jackson? Is Date a good field type for this?
Date
is a fine field type for this. You can make the JSON parse-able pretty easily by using ObjectMapper.setDateFormat
:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm a z");
myObjectMapper.setDateFormat(df);
In general, is there a way to process the variables before they get mapped to Object members by Jackson? Something like, changing the format, calculations, etc.
Yes. You have a few options, including implementing a custom JsonDeserializer
, e.g. extending JsonDeserializer<Date>
. This is a good start.
Related Topics
How to Do Case Insensitive String Comparison
Elements Order in a "For (… in …)" Loop
Why Would a JavaScript Variable Start With a Dollar Sign
Resizing an Iframe Based on Content
Is There a "Null Coalescing" Operator in JavaScript
JavaScript Raises Syntaxerror With Data Rendered in Jinja Template
How to Get All Properties Values of a JavaScript Object (Without Knowing the Keys)
How to Loop Through a Plain JavaScript Object With the Objects as Members
Async Function Returning Promise, Instead of Value
"Uncaught Syntaxerror: Cannot Use Import Statement Outside a Module" When Importing Ecmascript 6
How to Enable Cors in Angularjs
Xml Parsing of a Variable String in JavaScript
Combination of Async Function + Await + Settimeout
Jquery .Live() VS .On() Method For Adding a Click Event After Loading Dynamic Html
Set a Default Parameter Value For a JavaScript Function
How to Iterate Over a JavaScript Object