Issue
I get data from an API and the date comes in String value. I am converting String data to DateTime and trying to format it.
The problem is that the incoming data never comes as null. If it is null it comes as "N/A" and therefore gives an error. I think it gave an error while parsing because the data came in N/A form.
Data that didn't come in "N/A" format was perfectly formatted.
String endDate = "N/A";
if (data.endDate != null) {
var endDateTime = DateTime.parse(data.endDate!);
endDate = DateFormat('yyyy-MM-dd').format(endDateTime);
}
Is there a way to format the data or should I give up?
Solution
I would just use DateTime.tryParse
and check if the result is null
to indicate that parsing failed.
var endDateTime = DateTime.tryParse(data.endDate ?? '');
var endDate = (endDateTime == null)
? "N/A"
: DateFormat('yyyy-MM-dd').format(endDateTime);
Note that the above would use "N/A"
for any parsing failure.
Answered By - jamesdlin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.