Skip to content

dart:convert - serialize DateTime to ISO 8601 / RFC 3339  #16843

Closed

Description

@DartBot

This issue was originally filed by @MaxHorstmann


What steps will reproduce the problem?
=======================================

  1. Run this:

import 'dart:convert';
void main() {
  var dt = new DateTime.now();
  var json = JSON.encode(dt);
  print(json);
}

What is the expected output? What do you see instead?
=====================================================

Expected: current date/time, ISO 8601 formatted.
E.g. "2014-02-14T163300"

Throws "Converting object to an encodable object failed" instead.

What version of the product are you using? On what operating system?
====================================================================
Dart SDK version 1.0.0.3_r30188 on Windows and Ubuntu.

Please provide any additional information below.
================================================

ECMA-404 (JSON) unfortunately does not define a default serialization format for DateTime. However, ISO 8601 has become the de facto standard for DateTime serialization in JSON, widely adapted even on competing platforms. For example, even JSON.NET has moved away from a proprietary Microsoft/ODATA serialization format to ISO 8601: JamesNK/Newtonsoft.Json@fd760e3

DateTime in Dart already supports ISO 8601, see for instance DateTime.parse: https://api.dartlang.org/apidocs/channels/stable/#dart-core.DateTime@id_parse

I suggest to close the gap and also make it the default JSON serialization and deserialization format in dart:convert.

This will prevent Dart developers from coming up with their own serialization formats for DateTime, which would increase friction and decrease interoperability.

See also:

http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx

And, if I may link it here, my own recent blog post on the broader subject JSON+Dart:

http://maxhorstmann.net/2014/01/31/why-dart-should-learn-json-while-its-still-young (discussion on HN: https://news.ycombinator.com/item?id=7159926)

Activity

  1. kevmoo commented on Feb 15, 2014

    @kevmoo
    Member

    The issue: we want to ensure a perfect round-trip for any value we encode.

    Encoding a DateTime to a ISO 8601 String is great in theory, but on the way back it would be decoded into a String, not a DateTime


    Added Duplicate label.
    Marked as being merged into #16628.

  2. kevmoo commented on Feb 15, 2014

    @kevmoo
    Member

    For encoding, please use the toEncodable named paramater on JSON.encode to convert the DateTime as needed.


    Added Library-Convert label.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions