30

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

4
  • To be able to format your dates, Dart should know the format you're trying to parse. Check the intl package: pub.dev/packages/intl and pub.dev/documentation/intl/latest/intl/DateFormat-class.html
    – Arno
    Mar 19, 2020 at 8:18
  • @Arno seems like I need to have date too
    – AI.
    Mar 19, 2020 at 8:20
  • And, in any case (omitting locale differences), 'converting' to AM/PM is just :if(x > 12) x -12, I guess
    – Arno
    Mar 19, 2020 at 8:20
  • @Arno can you elaborate more?
    – AI.
    Mar 19, 2020 at 8:24

5 Answers 5

74

Use this code:

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

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

0
20

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'
1
  • 8
    In that case DateFormat.jm().format(DateFormat("hh:mm:ss").parse("22:30:00")) Mar 19, 2020 at 8:49
12

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);
}}
1
  • if i want to show seconds then how it possible? i tried this solution but it show only hour and minute Oct 4, 2021 at 10:37
8

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));
}
1
  • 1
    This is the only answer that works for both AM and PM times. Rest answers don't work for PM times. Thank You! Dec 27, 2021 at 6:32
0

Here is my solution a little simpler to understand I guess. And there is no need to add any library.

String getFormattedDateTime({d = "2022-11-15 14:21:37.152"}){
       List<String> months = [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December'
      ];

      List<String> days = [
        'Monday',
        'Tuseday',
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday',
        'Sunday',
      ];

      final dateTimeObj = DateTime.parse(d);

      // date format
      String fdate = "${days[dateTimeObj.weekday - 1].substring(0, 3)}, ${months[dateTimeObj.month-1].substring(0, 3)}-${dateTimeObj.day}";
      // time format
      String time = "${(dateTimeObj.hour > 12 ? dateTimeObj.hour - 12 : dateTimeObj.hour).abs()}:${dateTimeObj.minute} ${dateTimeObj.hour >= 12 ? "PM" : "AM"}";
      return "$fdate $time";
    }

This function will return formatted String something like this Tus, Nov-15 4:54 PM again you can format it accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.