我试图在点击按钮后在文本小部件中显示当前的日期时间。以下是可以的,但是我想改变格式。

当前的方法

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部分?


当前回答

这是我的简单解决方案。这并不需要任何依赖关系。

但是,日期将是字符串格式。如果你想要时间,那么改变子字符串的值

print(new DateTime.now()
            .toString()
            .substring(0,10)
     );   // 2020-06-10

其他回答

使用这种方法,不需要导入任何库。

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

如果用户是美国公民,但想看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())}'
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");

你可以从intl包中使用DateFormat。

import 'package:intl/intl.dart';

DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);

您可以使用DateTime.now()或clock.now()。带时钟库的样本:

import 'package:clock/clock.dart';

DateTime now = clock.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);