将字符串转换为日期时间时出错:字符串不能是日期时间的类型
我从 API 获取数据,日期以字符串值形式出现。我正在将字符串数据转换为日期时间并尝试对其进行格式化。
问题是传入的数据永远不会为空。如果它为空,则显示为“N/A”,因此会给出错误。我认为它在解析时出错,因为数据以 N/A 形式出现。
未采用“N/A”格式的数据已完美格式化。
String endDate = "N/A";
if (data.endDate != null) {
var endDateTime = DateTime.parse(data.endDate!);
endDate = DateFormat('yyyy-MM-dd').format(endDateTime);
}
有没有办法格式化数据还是我应该放弃?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我只会使用
DateTime.tryParse
并检查结果是否为null
表示解析失败。请注意,上面的内容将使用“N/A”来表示任何解析失败。
I would just use
DateTime.tryParse
and check if the result isnull
to indicate that parsing failed.Note that the above would use
"N/A"
for any parsing failure.像这样吗?:
让我知道。
Something like this?:
Let me know.
解决方案
Solution