Search
[Flutter/Dart] "Invalid date format" in DateTime parse
- M.R
- Aug 18, 2021
- 1 min read
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
}
Comments