Home > OS >  Error while converting String to DateTime: String cannot be type of DateTime
Error while converting String to DateTime: String cannot be type of DateTime

Time:03-05

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?

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

Solution

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