Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 223
ahmed minhaj Avatar asked Apr 07 '20 21:04

ahmed minhaj


People also ask

How do you convert 12 hours to 24 hours in Flutter?

Convert it to 24 hours format If we set alwaysUse24HourFormat to true, it might convert to 24 hours format but we need to clone the default setting and then change the value in somewhere.

How do you initialize TimeOfDay in Flutter?

You can create TimeOfDay using the constructor which requires both hour and minute or using DateTime object. Hours are specified between 0 and 23, as in a 24-hour clock. See also: showTimePicker, which returns this type.

How do you format a date in Flutter?

To format DateTime in Flutter using a standard format, you need to use the intl library and then use the named constructors from the DateFormat class. Simply write the named constructor and then call the format() method with providing the DateTime.


1 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

like image 74
Stefano Saitta Avatar answered Sep 21 '22 02:09

Stefano Saitta