Bashaar Shah
Bashaar Shah

Reputation: 35

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

Upvotes: 1

Views: 6636

Answers (2)

Doc
Doc

Reputation: 11651

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

Upvotes: 3

Edin
Edin

Reputation: 898

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

Upvotes: 0

Related Questions