我正在使用showTimePicker()抽空。
TimeOfDay _selectedTime;
Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay timePicked = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
);
if (timePicked != null)
setState(() {
_selectedTime = timePicked;
});
}
但是这里_selectedTime
是24小时格式。假设我选择3.00 PM,则显示15.00,即24小时制。
如何将这段时间转换为12小时格式?即应该显示3.00 PM,而不是15.00。
我可以编写逻辑来对其进行转换。但是有内置的功能吗?
答案 0 :(得分:3)
您可以使用hourOfPeriod
的{{1}}属性以12小时制返回小时。当然,那将没有AM-PM结尾:
TimeofDay
答案 1 :(得分:0)
我创建了一个用于将 TimeOfDay
解析为 12 小时格式的扩展
extension TimeOfDayExtensions on TimeOfDay {
String format12Hour(BuildContext context) {
TimeOfDay time = replacing(hour: this.hourOfPeriod);
MaterialLocalizations localizations = MaterialLocalizations.of(context);
final StringBuffer buffer = StringBuffer();
buffer
..write(time.format(context))
..write(' ')
..write(period == DayPeriod.am
? localizations.anteMeridiemAbbreviation
: localizations.postMeridiemAbbreviation);
return '$buffer';
}
你可以像这样使用
pickedTime?.format12Hour(context);
答案 2 :(得分:0)
使用 DateFormat
将时间转换为带有 AM & PM
TimeOfDay? _selectedTime;
Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay? timePicked = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
);
if (timePicked != null)
setState(() {
_selectedTime = timePicked;
});
// Conversion logic starts here
DateTime tempDate = DateFormat("hh:mm").parse(
_selectedTime!.hour.toString() +
":" + _selectedTime!.minute.toString());
var dateFormat = DateFormat("h:mm a"); // you can change the format here
print(dateFormat.format(tempDate));
}
输出:
颤动:晚上 8:00
颤动:凌晨 1:00
颤动:下午 6:00