[Flutter/Dart] "Invalid date format" in DateTime parse
Situation
(It's a mistake to say from the conclusion ...)
I convert DateTime type variable to String with dart and save it in shared preference. If you try to convert to DateTime type with parse method when reading from shared preference again, the above exception will occur.
class DaTa{
DateTime date;
var _formatter = new DateFormat('yyyy/MM/dd HH:mm');
//convert to json
Map toJson() {
//DateTime → String
String _formatted = _formatter.format(setting_changed_date);
return {
'date': _formatted,
};
}
//read from json
Data.fromJson(Map json){
//String → DateTime
date =DateTime.parse(json['date']); //exception here
}
}
Cause and Solution
You must use _formatter.parse () instead of DateTime.parse (). Since the format does not match, it becomes 'Invalid data format'.
Data.fromJson(Map json){
//String → DateTime
date = _formatter.parse(json['date']); //edit here
}
Recent Posts
See AllWhat want to do I want to create an input form using TextField. For example, if the input content is a monetary amount, I would like to...
What want to do There is a variable that remain unchanged once the initial value is determined. However, it cannot be determined yet when...
What want to do As the title suggests. Place two widgets in one line on the screen One in the center of the screen and the other on the...
Comments