简体   繁体   English

Flutter如何以确定的长度显示数字

[英]How to Display Number in Determined Lenght in Flutter

I have a very simple question.我有一个非常简单的问题。 I am working on time and date now and I have an issue.我现在正在按时间和日期工作,但我有一个问题。

Text('Time is: ${date.hour}:${date.minute}')

When I write something like this, where date is a DateTime object, when minute is less than 10, it is displayed like当我写这样的东西时,日期是 DateTime object,当分钟小于 10 时,它显示为

14:5

I want to display it in 14:05 format, in other words, in determined 2 digit lenght, like %.2d in C.我想以 14:05 格式显示它,换句话说,以确定的 2 位长度显示,例如 C 中的 %.2d。 How can I do it?我该怎么做?

You can do it with padLeft method .您可以使用padLeft 方法来完成。

${date.hour.toString().padLeft(2, "0")}:${date.minute.toString().padLeft(2, "0")}

In flutter, we can use the DateFormat method for this purpose.在 flutter 中,我们可以为此使用 DateFormat 方法。

import 'package:intl/intl.dart';

DateTime date = DateTime.now();
String formattedDate = DateFormat('HH:mm').format(date);

Text('Time is: $formattedDate')

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

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