Home > Software design >  How to convert the Time from "1hr 26min" format to just hour
How to convert the Time from "1hr 26min" format to just hour

Time:06-27

for example, I'm getting "1hr 26min" as Time I need to format it to an hour or just hours and minutes separately. how do I do that?

DateFormat.Hm().format(DateTime.parse(FetchList[index].Duration))
                                    .toString()

This was my unsuccessful approach.

CodePudding user response:

const hours = apiResponse.split('hr')[0];
const minutes = apiResponse.split(' ')[1].split('min')[0];

by - Jakob Schweighofer

CodePudding user response:

You can split the string and remove all char,

  final data = "1hr 26min";

  final separation = data.split(" ").toList();

  int hour =
      int.tryParse(separation.first.replaceAll(RegExp("[a-z]"), "")) ?? 0;
  int min = int.tryParse(separation.last.replaceAll(RegExp("[a-z]"), "")) ?? 0;
  print("h $hour min $min");

CodePudding user response:

You can parse the hour and minute values into a Duration object for further manipulation.

The implementation below is more efficient than using split, indexOf with multiple characters, or a regular expression.

const durationString = '1hr 26min';
final separatorIndex = durationString.indexOf(' ');
final hours = int.parse(durationString.substring(0, separatorIndex - 2));
final minutes = int.parse(durationString.substring(separatorIndex   1, durationString.length - 3));
final duration = Duration(hours: hours, minutes: minutes);

CodePudding user response:

try this

void datetimeConvert() {
String hr = '1hr 16min';
var splitValue = hr.split(' ');
print("Split Value ${splitValue}");
final Map<int, String> values = {for (int i = 0; i < 
splitValue.length; i  ) i: splitValue[i]};
 print(values);
 final value1 = values[0];
 final value2 = values[1];
 var aStr = value1?.replaceAll(new RegExp(r'[^0-9]'), ''); // '23'
 print("first ${aStr}");
 var aStr2 = value2?.replaceAll(new RegExp(r'[^0-9]'), ''); // '23'
 print("second ${aStr2}");
 }
  • Related