我试图在点击按钮后在文本小部件中显示当前的日期时间。以下是可以的,但是我想改变格式。
当前的方法
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部分?
当前回答
自从0.16以来有了一些变化这是我做的,
在pubspec.yaml中导入
dependencies:
flutter:
sdk: flutter
intl: ^0.16.1
然后 使用
txdate= DateTime.now()
DateFormat.yMMMd().format(txdate)
其他回答
这是我的简单解决方案。这并不需要任何依赖关系。
但是,日期将是字符串格式。如果你想要时间,那么改变子字符串的值
print(new DateTime.now()
.toString()
.substring(0,10)
); // 2020-06-10
你不能在dart中格式化日期,所以你需要使用外部包,我会推荐这篇文章: https://www.geeksforgeeks.org/format-dates-in-flutter/
您也可以使用这种语法。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}';
static String convertDateFormat(String dateTimeString, String oldFormat, String
newFormat) {
DateFormat newDateFormat = DateFormat(newFormat);
DateTime dateTime = DateFormat(oldFormat).parse(dateTimeString);
String selectedDate = newDateFormat.format(dateTime);
return selectedDate;
}
这样调用这个方法
convertDateFormat(inputDate, "dd-mm-yyyy", "d MMM yyyy");
使用这种方法,不需要导入任何库。
DateTime now = DateTime.now();
String convertedDateTime = "${now.year.toString()}-${now.month.toString().padLeft(2,'0')}-${now.day.toString().padLeft(2,'0')} ${now.hour.toString().padLeft(2,'0')}-${now.minute.toString().padLeft(2,'0')}";
输出
2020-12-05 14:57