'How to format TimeOfDay to String in flutter
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.
Solution 1:[1]
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
Solution 2:[2]
'${_currentTime.hour.toString().padLeft(2, '0')}:${_currentTime.minute.toString().padLeft(2, '0')}'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Stefano Saitta |
Solution 2 |