How to convert String to TimeOfDay in flutter?

like this:

TimeOfDay stringToTimeOfDay(String tod) {
  final format = DateFormat.jm(); //"6:00 AM"
  return TimeOfDay.fromDateTime(format.parse(tod));
}

This might seems hectic for newcomers or beginners, but you can easily convert String to DateTime and then DateTime to TimeOfDay.


Follow these steps for seamless conversion without messing anything up:

  1. add this package to pubspec.yaml : intl.

This package is necessary to convert any date string to a valid DateTime object.

  1. Convert your date string to a DateTime object like this way:

DateTime dateTime = DateFormat("h:mm a").parse(placement.startTime);

TimeOfDay timeOfDay = TimeOfDay.fromDate(dateTime)

There you have it. But don't forget to change your DateFormat String accordingly. For me, my date string was 4:30 AM, so my DateFormat string was "h:mm a". Change the DateFormat String as you need it to be. For DateFormat String references, follow this link


Try this

TimeOfDay _startTime = TimeOfDay(hour:int.parse(s.split(":")[0]),minute: int.parse(s.split(":")[1]));

This Worked for me..


You can do something like this:

TimeOfDay time = TimeOfDay(hour: s.split(":")[0], minute: s.split(":")[1]);

s is the string you wanna convert.

Tags:

Dart

Flutter