top of page

[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 All

Comments


category

Let's do our best with our partner:​ ChatReminder

iphone6.5p2.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Let's do our best with our partner:​ ChatReminder

納品:iPhone6.5①.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Theme diary: Decide the theme and record for each genre

It is a diary application that allows you to post and record with themes and sub-themes for each genre.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png
bottom of page