I'd like to (un)serialize a DateTime in a custom format, such as:
new DateFormat('M/d/yyyy');
Currently I get a runtime exception:
I/flutter (20794): FormatException: Invalid date format
I/flutter (20794): 04/10/2015
Is it possible using a method like this?
I think that the TypeHelper functionality could potentially solve this for you. I'm not 100% sure how to use it, but it seems like once it's documented it'll be a possibility.
This will be easily solved with https://github.com/dart-lang/json_serializable/pull/146
See here for how you can get this done w/out creating a custom TypeHelper.
Will be published soon!
Thanks! I got this to work. Leaving a DateTime with a custom format example for others:
@JsonSerializable()
class Test extends Object with _$TestSerializerMixin {
@JsonKey(fromJson: _fromJson, toJson: _toJson)
final DateTime date;
Test({
this.date,
});
factory Test.fromJson(Map<String, dynamic> json) => _$TestFromJson(json);
}
final _dateFormatter = new DateFormat('M/d/yyyy');
DateTime _fromJson(String date) => _dateFormatter.parse(date);
String _toJson(DateTime date) => _dateFormatter.format(date);
So glad!
On Thu, May 10, 2018, 21:57 Seth Westphal notifications@github.com wrote:
Thanks! I got this to work. Leaving a DateTime with a custom format
example for others:@JsonSerializable()class Test extends Object with _$TestSerializerMixin {
@JsonKey(fromJson: _fromJson, toJson: _toJson)
final DateTime date;Test({
this.date,
});factory Test.fromJson(Map
json) => _$TestFromJson(json);
}
final _dateFormatter = new DateFormat('M/d/yyyy');DateTime _fromJson(String date) => _dateFormatter.parse(date);String _toJson(DateTime date) => _dateFormatter.format(date);—
You are receiving this because you modified the open/close state.
Reply to this email directly, view it on GitHub
https://github.com/dart-lang/json_serializable/issues/133#issuecomment-388259781,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AABCipPS02eJgTawgajudDj26k8R5y-Yks5txRo9gaJpZM4TNoUJ
.
Ah, its gotta be a static member.
static final _dateFormatter = DateFormat('M/d/yyyy');
static DateTime _fromJson(String date) => _dateFormatter.parse(date);
static String _toJson(DateTime date) => _dateFormatter.format(date);
Most helpful comment
Thanks! I got this to work. Leaving a
DateTimewith a custom format example for others: