Sachin Soma
Sachin Soma

Reputation: 3802

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

Upvotes: 0

Views: 1366

Answers (4)

AlexFlutter
AlexFlutter

Reputation: 123

I am using this, as time is irrelevant I used the DateTime.now() Time

This is being used in a datefield

final departureTime = "11:00 AM"; // Formatted By `DateFormat.jm()`

final initialDateValue = DateTime.tryParse(
 "${DateTime.now().toIso8601String().split("T").first} ${departureTime ?? ''}"
),

Upvotes: 0

Kaushik Chandru
Kaushik Chandru

Reputation: 17772

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

Upvotes: 0

Gitesh kumar Jha
Gitesh kumar Jha

Reputation: 347

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

Upvotes: 0

quoci
quoci

Reputation: 3557

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"

Upvotes: 1

Related Questions