我试图在点击按钮后在文本小部件中显示当前的日期时间。以下是可以的,但是我想改变格式。
当前的方法
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部分?
当前回答
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.toIso8601String().split("T")[0];
获得时间:
datetime.toIso8601String().split("T")[1];
您可以使用DateTime.now()或clock.now()。带时钟库的样本:
import 'package:clock/clock.dart';
DateTime now = clock.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);
您也可以使用这种语法。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}';
如果用户是美国公民,但想看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())}'
你可以从intl包中使用DateFormat。
import 'package:intl/intl.dart';
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);