'Parse only time with AM/PM in flutter

I am trying to parse time in format 10:15 AM. But it is showing FormatException: Invalid date format 10:15 AM

My code

DateFormat.jm().format(DateTime.parse('10:15 AM'));

Also tried

DateFormat('h:mm a').format(DateTime.parse('10:15 AM'));


Solution 1:[1]

This happens because 10:15 AM the Datetime.parse method don't accept this format. Here are some example of accepted strings which can be found in the documentation.

  • "2012-02-27"
  • "2012-02-27 13:27:00"
  • "2012-02-27 13:27:00.123456789z"
  • "2012-02-27 13:27:00,123456789z"
  • "20120227 13:27:00"
  • "20120227T132700"
  • "20120227"
  • "+20120227"
  • "2012-02-27T14Z"
  • "2012-02-27T14+00:00"
  • "-123450101 00:00:00 Z": in the year -12345.
  • "2002-02-27T14:00:00-0500": Same as "2002-02-27T19:00:00Z"

Solution 2:[2]

String input = '10:30 PM';
DateTime startDatetime = newDateFormat.jm().format(DateFormat.jm().parse(input));

Solution 3:[3]

You will take date month and year to parse it. Try creating a reference to current date

String timeString = 10:30 AM;
final now = DateTime.now().toUtc();

Next convert the string into hours and minutes. You can also use regex but to keep it simple let's split it.

int hour = int.parse(timeString.split(":")[0]);
int minute = timeString.split(":")[1].split(" PM")[0];
bool isPm = timeStrig.contains("AM")?true:false;

Now if you parse the string with date it should work.

DateTime.utc(now.year, now.month, now.day, isPm ? hour + 12 : hour, minute, second);

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 quoci
Solution 2 Gitesh kumar Jha
Solution 3