1988
1988

Reputation: 329

How to convert TimeOfDay in dart into a string

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

Upvotes: 1

Views: 836

Answers (2)

Kashif Ahmad
Kashif Ahmad

Reputation: 263

This will work also

"${_time.hour}:${_time.minute}"

Upvotes: 0

Chance
Chance

Reputation: 1654

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

Upvotes: 1

Related Questions