繁体   English   中英

Flutter:“DateTime”类型不是“String”类型的子类型

[英]Flutter: type 'DateTime' is not a subtype of type 'String'

Text(
        DateTime.parse(documents[index]['createdAt']
                                  .toDate()
                                  .toString()) ??
                              'default',
)

我正在尝试从 firestore 获取日期。 我将 DateTime.now() 存储在 firestore 的 createdIn 中。

因为两者的格式不一样。

  1. 第 1 步:您可以创建 DateFormat。
  2. 第 2 步:使用“DateFormat”.parse()。

尝试阅读此内容: https ://help.talend.com/r/6K8Ti_j8LkR03kjthAW6fg/atMe2rRCZqDW_Xjxy2Wbqg

在这里,它期望类型为“String”,但我们将其作为“DateTime”传递,这是不正确的。

以默认的“en_US”格式格式化日期不需要任何初始化。

https://api.flutter.dev/flutter/intl/DateFormat-class.html

因此,我们只需要将其格式化为:

var dateTime = DateTime.now()
DateFormat.E().format(dateTime)

E() 是 Flutter 中 DateFormat 的构造函数,它指的是星期的前 3 个字母

您可以参考官方文档以获取可用的构造函数:

https://api.flutter.dev/flutter/intl/DateFormat-class.html#constructors

注意:以下是用于 DateTime 库的版本 ~ intl intl: ^0.18.0

( https://pub.dev/packages/intl )

如果它是时间戳字段,则将其转换为时间戳。 如果您需要它作为 DateTime,请在其上使用 a.toDate。 不要通过字符串处理它......完全没有必要。

它可能对你有帮助

  String? changeDateFormatWithInput(String? currentDate, currentFormat,
  requiredFormat) {
String? date;

try {
  if (currentDate != null && currentDate.isNotEmpty) {
    DateTime tempDate =
    new DateFormat(currentFormat).parse(currentDate, true);
    date = DateFormat(requiredFormat).format(tempDate.toLocal());
    return date;
  }
} catch (e) {
  print(e);
  return null;
}
return date;

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM