【问题标题】:How to get a localized date string in flutter?如何在颤动中获取本地化的日期字符串?
【发布时间】:2021-07-06 04:06:01
【问题描述】:

在 Flutter 中,如何获得与用户(或设备)语言设置相匹配的格式正确的日期字符串?

例如:

在英语中,日期通常写为“Frid​​ay April 10”,在德语中通常写为“Freitag 10. April”。 根据docs,必须调用initializeDateFormatting() 才能启用来自DateFormat 的本地化结果。在代码中是这样的:

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';

class DateTimeDisplay extends StatefulWidget {
  DateTimeDisplay({Key? key}) : super(key: key);

  @override
  _DateTimeDisplay createState() => _DateTimeDisplay();
}

class _DateTimeDisplay extends State<DateTimeDisplay> {
  @override
  void initState() {
    super.initState();

    initializeDateFormatting().then((_) => setState(() {}));
  }

  @override
  Widget build(BuildContext context) {
    DateTime now = new DateTime.now();
    String dayOfWeek = DateFormat.EEEE().format(now);
    String dayMonth = DateFormat.MMMMd().format(now);
    String year = DateFormat.y().format(now);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Text(dayOfWeek, textAlign: TextAlign.center),
        Text(dayMonth, textAlign: TextAlign.center),
        Text(year, textAlign: TextAlign.center),
      ],
    );
  }
}

问题是,DateFormat.EEEE().format(now); 总是以英文返回日期。同DateFormat.MMMMd().format(now);,只回复英文月份和日期/月份顺序。

您有什么想法吗?或者如何说服颤振返回正确本地化的日期?非常感谢您的建议。谢谢。

【问题讨论】:

    标签: flutter localization


    【解决方案1】:

    您可以通过在 DateFormater 中传递区域设置来使用第二种方法,如下面的代码:

    String locale = Localizations.localeOf(context).languageCode;
    DateTime now = new DateTime.now();
    String dayOfWeek = DateFormat.EEEE(locale).format(now);
    String dayMonth = DateFormat.MMMMd(locale).format(now);
    String year = DateFormat.y(locale).format(now);
    

    DateFormat 的每个命名构造函数都将locale 作为可选的位置参数。

    在这种情况下,您甚至不需要使您的小部件有状态。

    【讨论】:

    • 就是这样。非常感谢!
    【解决方案2】:

    查看文档后,我相信您需要告诉软件包您要使用哪个语言环境。尝试使用您要使用的语言环境字符串将参数传递给initializeDateFormatting()

    import 'package:intl/date_symbol_data_local.dart';
    
    initializeDateFormatting('fr_FR', null).then((_) => runMyCode());
    

    要从设备获取区域设置,请使用:

    import 'dart:io';
    
    final String defaultLocale = Platform.localeName; // Returns locale string in the form 'en_US
    

    字体:How to get timezone, Language and County Id in flutter by the location of device in flutter?

    【讨论】:

    • 爱德华多,感谢您的帮助。不幸的是,它不起作用:DateFormat.EEEE().format() 一直用英语返回天数。毫不奇怪,考虑到initializeDateFormatting() 的文档提到:“locale 和 ignored 参数都被忽略,因为所有语言环境的数据都是直接可用的。”所以我想这里还有其他问题。 ..你有什么想法吗?
    猜你喜欢
    • 2021-01-16
    • 2012-08-20
    • 2014-11-16
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多