Datetime 将时间转换为am/pm颤振
如何将时间转换为上午/下午 我有这个输出Datetime 将时间转换为am/pm颤振,datetime,flutter,dart,Datetime,Flutter,Dart,如何将时间转换为上午/下午 我有这个输出 I/flutter (17720): 9:00:00 I/flutter (17720): 11:00:00 I/flutter (17720): 12:00:00 这就是我尝试过的 final item = snapshot.data[index]; print("Time " + item['time'].toString()); DateTime dateTime = DateTime.parse(item['time'].toStrin
I/flutter (17720): 9:00:00
I/flutter (17720): 11:00:00
I/flutter (17720): 12:00:00
这就是我尝试过的
final item = snapshot.data[index];
print("Time " + item['time'].toString());
DateTime dateTime = DateTime.parse(item['time'].toString());
print(DateUtil().formattedTime(dateTime));
DateUtil
String formattedTime(DateTime dateTime) {
return DateFormat().add_jm().format(dateTime);
}
错误
Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: _con.selectedTime,
);
if (picked != null) {
String selTime =
picked.hour.toString() + ':' + picked.minute.toString() + ':00';
print(DateFormat.jm().format(DateFormat("hh:mm:ss").parse(selTime)));
}}
_selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: _con.selectDateAndTime,
firstDate: DateTime(2021),
lastDate: DateTime(2040),
);
if (picked != null) {
print(picked);
}}
I/颤振(17720):时间09:00:00
════════ widgets库捕获到异常
═══════════════════════════════════ 发生了以下格式化异常
抛出的建筑标记(脏,状态:TagsState#b3a2f):无效日期
格式09:00:00
您可以使用intl库 并格式化日期时间 DateFormat.yMEd().add_jms().format(DateTime.now()); ==>“Thu,5/23/2013 10:21:47 AM”使用以下代码:
DateFormat('hh:mm a').format(DateTime.now());
根据intl库,它表示a代表AM/PM。
DateFormat用于以区域设置敏感的方式格式化和分析日期
转换时间
print(DateFormat.jm().format(DateFormat("hh:mm:ss").parse("14:15:00")));
print(DateFormat('yyyy-MMMM-dd').format("2021-05-14 00:00:00.000"));
输出:凌晨3:20
转换日期
print(DateFormat.jm().format(DateFormat("hh:mm:ss").parse("14:15:00")));
print(DateFormat('yyyy-MMMM-dd').format("2021-05-14 00:00:00.000"));
输出:2021-2014年5月
示例:
时间选择器
Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: _con.selectedTime,
);
if (picked != null) {
String selTime =
picked.hour.toString() + ':' + picked.minute.toString() + ':00';
print(DateFormat.jm().format(DateFormat("hh:mm:ss").parse(selTime)));
}}
_selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: _con.selectDateAndTime,
firstDate: DateTime(2021),
lastDate: DateTime(2040),
);
if (picked != null) {
print(picked);
}}
为了能够格式化日期,Dart应该知道您试图解析的格式。检查intl包:@Arno似乎需要使用date,并且在任何情况下(忽略区域设置差异),“转换”为AM/PM只是:如果(x>12)x-12,则guess@Arno你能详细说明一下吗?在这种情况下,
DateFormat.jm().format(DateFormat(“hh:mm:ss”).parse(“22:30:00”)
这是一个简单的答案,谢谢!