在 Flutter 中,如何获得与用户(或设备)的语言设置相匹配的格式正确的日期字符串?
例如:
在英语中,日期通常写作“Friday April 10”,在德语中通常写作“Freitag 10. April”。
根据{{3}},必须调用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);
相同,仅回复英文月份和日期/月份顺序。
你有什么想法这里可能有什么问题吗?或者如何说服颤振返回正确本地化的日期?非常感谢您的建议。谢谢。
答案 0 :(得分: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
作为可选的位置参数。
在这种情况下,您甚至不需要使小部件有状态。
答案 1 :(得分:0)
查看文档后,我相信您需要告诉包您要使用哪种语言环境。尝试使用您要使用的语言环境字符串将参数传递给 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?