我试图在点击按钮后在文本小部件中显示当前的日期时间。以下是可以的,但是我想改变格式。
当前的方法
DateTime now = DateTime.now();
currentTime = new DateTime(now.year, now.month, now.day, now.hour, now.minute);
Text('$currentTime'),
结果
YYYY-MM-JJ HH-MM: 00.000
问题
如何移除:00.000部分?
我试图在点击按钮后在文本小部件中显示当前的日期时间。以下是可以的,但是我想改变格式。
当前的方法
DateTime now = DateTime.now();
currentTime = new DateTime(now.year, now.month, now.day, now.hour, now.minute);
Text('$currentTime'),
结果
YYYY-MM-JJ HH-MM: 00.000
问题
如何移除:00.000部分?
当前回答
如果用户是美国公民,但想看24小时格式的一切-然后 显示12/24小时的地区将不满足用户
// getting system settings 12/24 h format
if (MediaQuery.of(context).alwaysUse24HourFormat){
timeFormat = new DateFormat("kk:mm", languageCode); //24h format
}
else{
timeFormat = new DateFormat("KK:mm a", languageCode); //12h format
}
//then use it:
'${timeFormat.format DateTime.now())}'
其他回答
自从0.16以来有了一些变化这是我做的,
在pubspec.yaml中导入
dependencies:
flutter:
sdk: flutter
intl: ^0.16.1
然后 使用
txdate= DateTime.now()
DateFormat.yMMMd().format(txdate)
您也可以使用这种语法。YYYY-MM-JJ HH-MM:
var now = DateTime.now();
var month = now.month.toString().padLeft(2, '0');
var day = now.day.toString().padLeft(2, '0');
var text = '${now.year}-$month-$day ${now.hour}:${now.minute}';
使用这个函数
todayDate() {
var now = new DateTime.now();
var formatter = new DateFormat('dd-MM-yyyy');
String formattedTime = DateFormat('kk:mm:a').format(now);
String formattedDate = formatter.format(now);
print(formattedTime);
print(formattedDate);
}
输出:
08:41:AM
21-12-2019
你不能在dart中格式化日期,所以你需要使用外部包,我会推荐这篇文章: https://www.geeksforgeeks.org/format-dates-in-flutter/
这是我的简单解决方案。这并不需要任何依赖关系。
但是,日期将是字符串格式。如果你想要时间,那么改变子字符串的值
print(new DateTime.now()
.toString()
.substring(0,10)
); // 2020-06-10