我有一个时间选择器,显示用户选择的当前时间。我能够将其从24小时格式转换为12小时格式。但是我希望它也显示AM和PM,而不仅仅是AM。有什么方法可以使用TimeOfDay数据类型显示AM和PM的时间吗?欢迎任何建议。
Future<Null> selectTime(BuildContext context) async {
TimeOfDay timePicked = await showTimePicker(
context: context,
initialTime: _currentTime,
);
if (timePicked != null && timePicked != _currentTime) {
setState(() {
_currentTime = timePicked;
print("Time Selected : ${_currentTime.toString()}");
_currentTime = timePicked.replacing(hour: timePicked.hourOfPeriod); //this gets it in 12 hour format
Fluttertoast.showToast(
msg:
"${_currentTime.format(context)}",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 1,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 16.0);
});
}
}
最佳答案
import 'package:flutter/material.dart';
void main() {
TimeOfDay noonTime = TimeOfDay(hour: 15, minute: 0); // 3:00 PM
TimeOfDay morningTime = TimeOfDay(hour: 5, minute: 0); // 5:00 AM
print(noonTime.period); // gives DayPeriod.pm
print(morningTime.period); // gives DayPeriod.am
//example 1
if (noonTime.period == DayPeriod.am)
print("$noonTime is AM");
else
print("$noonTime is PM");
//example 2
if (morningTime.period == DayPeriod.am)
print("$morningTime is AM");
else
print("$morningTime is PM");
}
关于flutter - 在flutter中从24小时格式转换为12小时格式时,添加AM或PM,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61135712/