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.
CodePudding user response:
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;
}