'Convert time to am/pm flutter

How to convert the time to am/pm ?

I have this output

I/flutter (17720): 9:00:00
I/flutter (17720): 11:00:00
I/flutter (17720): 12:00:00

This is what I have tried

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

Error

I/flutter (17720): Time 09:00:00

════════ Exception caught by widgets library ═══════════════════════════════════ The following FormatException was thrown building Tags(dirty, state: TagsState#b3a2f): Invalid date format 09:00:00



Solution 1:[1]

You can use the intl library https://pub.dev/packages/intl and format your DateTime

 DateFormat.yMEd().add_jms().format(DateTime.now());

Output:

'Thu, 5/23/2013 10:21:47 AM'

Solution 2:[2]

Use this code:

DateFormat('hh:mm a').format(DateTime.now());

According to the intl library, it states that a represents AM/PM.

Solution 3:[3]

DateFormat class

DateFormat is for formatting and parsing dates in a locale-sensitive manner.

Convert Time

print(DateFormat.jm().format(DateFormat("hh:mm:ss").parse("14:15:00")));

Output : 3:20 AM

Convert Date

print(DateFormat('yyyy-MMMM-dd').format("2021-05-14 00:00:00.000"));

Output : 2021-May-14

EXAMPLE :

Time Picker

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

Date Picker

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

Solution 4:[4]

this function can helps to convert only time, Without date

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

String formatedTime(TimeOfDay selectedTime) {
DateTime tempDate = DateFormat.Hms().parse(selectedTime.hour.toString() +
  ":" +
  selectedTime.minute.toString() +
  ":" +
  '0' +
  ":" +
  '0');
var dateFormat = DateFormat("h:mm a");
return (dateFormat.format(tempDate));
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MendelG
Solution 2 user14761376
Solution 3
Solution 4 MhdBasilE