Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parsing Date from MongoDb in Flutter always fails

I’m trying to parse a Date signUpDate field from MongoDb User object received via http request into a Flutter DateTime signUpDate but it always fails. In my User Schema I have signUpDate: { type: Date, required: false, default: Date.now },. In my Flutter factory User.fromMongoDB(Map<String, dynamic> map) helper I’m using signUpDate: DateTime.parse(map['signUpDate']). When printing http response signUpDate is "signUpDate":"2021-12-15T11:10:01.521Z". Is it just the format coming back from mongo not parsable by DateTime parser or I’m parsing it wrongly?
Many thanks.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here the code for parsing ISO8601 string to Date time just passing what format you need.

import 'package:intl/intl.dart';

void main() {
  var data = "2021-12-15T11:10:01.521Z";

  DateTime dateTime = getFormattedDateFromFormattedString(
      value: data,
      currentFormat: "yyyy-MM-ddTHH:mm:ssZ",
      desiredFormat: "yyyy-MM-dd HH:mm:ss");
  
  print(dateTime); //2021-12-15 11:10:01.000
}

getFormattedDateFromFormattedString(
    {required value,
    required String currentFormat,
    required String desiredFormat,
    isUtc = false}) {
  DateTime? dateTime = DateTime.now();
  if (value != null || value.isNotEmpty) {
    try {
      dateTime = DateFormat(currentFormat).parse(value, isUtc).toLocal();
    } catch (e) {
      print("$e");
    }
  }
  return dateTime;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading