How to format TimeOfDay to String in flutter

Viewed 17132

I want to display the current time. Used TimeOfDay.Now() to get the current time,

TimeOfDay _currentTime = TimeOfDay.now();

Text("Current Time: ${_currentTime.toString()}")

Used Text() widget to display time, but it displays TimeOfDay(22.30) instead of 10.30pm.

How to remove TimeOfDay from TimeOfDay(22.30), want to display only 10.30pm.

2 Answers

Doing a toString to a TimeOfDay object will return you the default implementation of toString which as per documentation:

Returns a string representation of this object.

What are you looking for here is to format it instead.

TimeOfDay _currentTime = TimeOfDay.now();
Text("Current Time: ${_currentTime.format(context)}")

Please also take a look at the official documentation in order to have a better understanding of why toString is not doing what you expect.

https://api.flutter.dev/flutter/material/TimeOfDay-class.html

'${_currentTime.hour.toString().padLeft(2, '0')}:${_currentTime.minute.toString().padLeft(2, '0')}'
Related