flutter - 如何在 Dart 中格式化时间?

标签 flutter dart

我试图构建一个应给出维也纳本地时间的应用程序。我用 time = DateFormat.jm().format() 格式化了时间,但现在我得到了像 14:25 PM 这样的时间。我怎样才能删除 PM,因为我不需要它? 这是我试过的代码:

class _MyHomePageState extends State<MyHomePage> {
  void getTime() async {
    String time;

    Response response =
        await get("http://worldtimeapi.org/api/timezone/Europe/Vienna");
    Map data = jsonDecode(response.body);

    String datetime = data["datetime"];
    String offset = data["utc_offset"].substring(1, 3);
    DateTime now = DateTime.parse(datetime);
    now = now.add(Duration(hours: int.parse(offset)));
    time = DateFormat.jm().format(now);
    print(time);
  }

这是我得到的时间:

I/flutter ( 9302): 12:43 PM

最佳答案

如果您使用的是 Intl package那么您只需提供一个自定义格式化程序就可以做到这一点而无需太多工作。

对于您的用例,您需要使用格式化程序 HH:mm,它仅代表小时和分钟。

final date = DateTime.now();
final hourAndMinues = DateFormat('HH:mm').format(date);

print(hourAndMinutes); // 12:00

关于flutter - 如何在 Dart 中格式化时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61850590/

相关文章:

flutter - 如何在 Dart 中从两个不同的列表创建公共(public)元素的列表?

flutter - 创建数据库时 I/flutter ( 9532) : Binding has not yet been initialized,

rest - 将我的 Postman 调用转换为 Dart/Flutter API 调用

dart - 如何将函数作为可选参数传递给 dart 函数中的默认值?

dart - Widget 消失时如何取消正在运行的 Timer()

dart - 如何在 Dart 中使用 int 与在 c# 或 java 中使用 int 相同

Flutter - 堆叠在一张条形图中的水平条形图

java - 插件的 Flutter 构建失败,找不到类文件

flutter : Target file "lib/main.dart" not found

flutter - 获取用户的 Flutter Web 位置