flutterdarttimeofday

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


I have a time-picker that displays the current time the user selects. I am able to convert it from 24 hour to 12 hour format. But I want it to also display AM and PM, not just AM. Is there any way to show the time with AM and PM using the TimeOfDay datatype? Any suggestions are welcome.

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

Solution

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