'Error while converting String to DateTime: String cannot be type of DateTime

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 1:[1]

Something like this?:

var endDateTime = DateTime.parse(data.endDate!);

String endDate = (!data.endData || data.endData === 'N/A') ? 'N/A' : DateFormat('yyyy-MM-dd').format(endDateTime)

Let me know.

Solution 2:[2]

Solution

 String endDate = "N/A";
    if (data.endDate!.length > 3) {
      var endDateTime = DateTime.parse(data.endDate!);
      endDate = DateFormat('yyyy-MM-dd').format(endDateTime);
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 regenin