在 flutter 中从 24 小时格式转换为 12 小时格式时添加 AM 或 PM

Add AM or PM when converting from 24 hour to 12 hour format in flutter

我有一个时间选择器,可以显示用户选择的当前时间。我可以将它从 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);
      });
    }
  }

您只需要查看 24 小时格式的 _currentTime 是否大于 12,如果是,则为下午,如果不是,则为上午

希望对您有所帮助

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");
}