如何仅从DateTime.now()中提取时间; [英] How to extract only the time from DateTime.now();

查看:607
本文介绍了如何仅从DateTime.now()中提取时间;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个变量来从 DateTime.now();

DateTime date = DateTime.now();
String time = "${date.hour}:${date.minute}:${date.second}";

问题是,例如,如果时间是01:09:32,我得到的时间是1:9:32。

The problem is if the time for example is 01:09:32, the time that i get is 1:9:32.

我该如何使用常规格式的时间?

How do i get the time with the regular format?

我可以做这与if-else一起使用,但是我敢肯定有更好的方法

I can do this with if-else, but i'm sure there is a better way

推荐答案

您可以尝试使用DateFormat,对您的pubspec.yaml包括 intl 依赖项

You can try to use a DateFormat, just include intl dependency to your pubspec.yaml

import 'package:intl/intl.dart';

DateTime now = DateTime.now();
String formattedTime = DateFormat.Hms().format(now);
print(formattedTime);

根据您的要求,您可以查看 DateFormat

Depending on what your requirements is, you can look at DateFormat

从DateFormat类获取的一些示例可为您提供帮助

Some examples taken from DateFormat-class to help you a bit more.

String formattedTime = DateFormat.jm().format(now);           //5:08 PM
String formattedTime = DateFormat.Hm().format(now);           //17:08  force 24 hour time

这篇关于如何仅从DateTime.now()中提取时间;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆