Home > OS >  How to convert TimeOfDay in dart into a string
How to convert TimeOfDay in dart into a string

Time:09-22

I want to convert TimeOfDay from API into a string and show it in table. The problem is, i don't know how to convert it into a string

    class UserInfo {
      String tanggal = DateFormat("yyyy-MM-dd").format(DateTime.now());
      TimeOfDay pulang;
      
    
      UserInfo(
          this.pulang,
          this.tanggal,
          );
        }

CodePudding user response:

Declare an extension in some file of your choice.

extension MemberTimeOfDay on TimeOfDay {
  String get toStringFormat {
    var time = this;
    return '${_twoDigits(time.hour)}:${_twoDigits(time.minute)}';
  }

  static String _twoDigits(int n) {
    if (n >= 10) return '$n';
    return '0$n';
  }
}

Then just create the timeofDay object and use the extension property, when using the property it is necessary to import the extension file.

var timeofDay = TimeOfDay.now();
print(timeofDay.toStringFormat);

//or

var now = DateTime.now();
var timeofDayDate = TimeOfDay(hour: now.hour, minute: now.minute);
print(timeofDayDate.toStringFormat);

Without extension, it would be enough to create the timeofDay object and print or add it to the string like this.

var now = DateTime.now();
var timeofDayDate = TimeOfDay(hour: now.hour, minute: now.minute);
var time = '${timeofDayDate.hour}:${timeofDayDate.minute}';
print(time);
  • Related