[英]Dart / Flutter: I am trying to convert a String to a Date but getting an Exception
In my app, there are some situations where the date
field in the JSON is invalid.在我的应用程序中,有些情况下 JSON 中的date
字段无效。 Instead of displaying "Invalid date" I would like to display another field called timestamp
.我不想显示“无效日期”,而是想显示另一个名为timestamp
的字段。 This field, however, is at this format: 20200518100014
.但是,此字段采用以下格式: 20200518100014
。 I would like to convert that to May 18, 2020
.我想将其转换为May 18, 2020
。
I have not been successful and this is the latest code I have我没有成功,这是我拥有的最新代码
String processDate(data) {
var timeStamp = DateFormat("MMM dd, yyyy").parse(data.timestamp.toString());
return data.date == 'Invalid date' ? timeStamp : data.date;
}
This causes the following error:这会导致以下错误:
How can I fix this issue to display the date as May 18, 2020
format instead.如何解决此问题以将日期显示为May 18, 2020
格式。
ANSWER :答案:
Based on @Lunedor answer below, I was able to create the following solution:基于下面的@Lunedor 答案,我能够创建以下解决方案:
String processDate(data) {
String date = data.timestamp.toString();
String dateWithT = date.substring(0, 8) + 'T' + date.substring(8);
String dateTime = DateFormat("MMM dd, yyyy").format(DateTime.parse(dateWithT));
return data.date == 'Invalid date' ? dateTime : data.date;
}
I am skipping MMM mistake, check this answer to see what type of strings can be parse as time and date:我正在跳过 MMM 错误,请检查此答案以查看可以将哪种类型的字符串解析为时间和日期:
https://stackoverflow.com/a/60988096/12880676 https://stackoverflow.com/a/60988096/12880676
And your case you can use the method in this answer .而你的情况,你可以使用这个答案中的方法。 I am just copy and paste the code:我只是复制并粘贴代码:
String date = '20180626170555';
String dateWithT = date.substring(0, 8) + 'T' + date.substring(8);
DateTime dateTime = DateTime.parse(dateWithT);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.