首页 > 解决方案 > 如何在颤动中使用 DateTime.now() 仅显示当前时间?

问题描述

 DateTime currentTime = new DateTime.now();

  Widget CustomCards(Color frontColor, String fetchTime) {
    Card cards = new Card(
      elevation: 1.0,
      margin: const EdgeInsets.symmetric(horizontal: 2.0, vertical: 2.0),
      color: bgColor,
      shape: new RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(15.0),
      ),
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(5.0),
            child: Row(
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 15.0),
                  child: Text(
                  currentTime.toString(),
                  style: new TextStyle(
                    fontStyle: FontStyle.italic,
                    fontFamily: 'Satisfy',
                    fontSize: 15.0,
                    color: frontColor,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
    return cards;
  }

如何从 DateTime 显示当前时间,因为它始终显示当前日期和时间,但我想以hh:mm:ss 格式显示时间。这里的秒应该是他们的。我找不到任何逻辑,请帮助我。谢谢你

标签: androidflutterdatetimeflutter-layoutflutter-test

解决方案


在 pubspec.yaml 中添加依赖项intl: ^0.16.1(检查 pub.dev 中的最新依赖项),然后您可以DateFormat.yMMMd().format(DateTime.now());在 dart 文件中使用。您可以根据需要更改日期格式的模式。

对于 DateFormat 集中不存在的自定义日期模式,您可以使用

DateFormat('hh:mm:ss').format(DateTime.now());

推荐阅读