1

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);
      });
    }
  }
Bashaar Shah
  • 35
  • 1
  • 3

2 Answers2

3
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");
}
Doc
  • 10,831
  • 3
  • 39
  • 63
  • Thanks, this worked for displaying AM and PM. For the time, I ended up creating another variable to which I had it display the hour and time in the 12 hour format. I then split the "TimeOfDay" prefix, and then replaced the "(" and ")" with "" (an empty space so that it would be formatted just as I wanted). – Bashaar Shah Apr 10 '20 at 15:19
0

you just need to look if _currentTime in the 24 hour format is bigger than 12 if yes its PM if no its AM

hope it helped

Edin
  • 758
  • 6
  • 18