How to format TimeOfDay to String in flutter - date

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.

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

Display Int or Double Widget Equivalent to Text()?

I want to display a double (or int) similar to how you would a string with a Text() widget. Is there an equivalent to this widget for ints or doubles in Flutter? Sorry if this is obvious, but I could not find anything.
Text("${<Your double/int variable>"})
You use a Text widget for this as well, simply use string interpolation to display your variables as a String:
final int two = 2;
final double pi = 3.14;
return Text("$two is an integer, and $pi is a double.");
You can also use the toString() method on any object in Dart (which is what the string interpolation above does implicitly). So if you want to print a double by itself, it's possible to write:
Text(pi.toString());
More on Strings and interpolation

Time in 24 hour format showing in 12 hour format in flutter

I'm trying to print the time in 24-hour format as selected from the Time Picker method. However, every time I select a time that is in a 24-hour format, it somehow converts it into its 12-hour format. Let's say I selected 22:30 on the Time Picker Widget, it prints 10:30 instead of 22:30. Can someone please shed some light on this?
Here is my code:
TimeOfDay _toTime = TimeOfDay.now();
String closingTime = '';
InkWell(
onTap: () => showTimePicker(
context: context,
initialTime: _toTime,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(context).copyWith(
alwaysUse24HourFormat: true),
child: child ?? Container()))
.then((value) {
setState(() {
_toTime = value!;
var dt = DateFormat('HH:mm').parse(_toTime.format(context));
closingTime = DateFormat('HH:mm').format(dt);
print('CLOSING TIME: $closingTime');
});
})
You can try to use a DateFormat instead of TimeOfDay, just include intl dependency
First parse the value to a date, then format it how you want
import 'package:intl/intl.dart';
DateTime date= DateFormat.now();
// format date
print(DateFormat("HH:mm").format(date));
you can use different characters to achieve the result for example:
h hour in am/pm (1~12)
H hour in day (0~23)
k hour in day (1~24)
K hour in am/pm (0~11)
Refrence:
Flutter dateformat
Intl package

SetState in ternary operator

I want to change the color of the text displaying the scheduled time, if the scheduled time is past the current time then it should change to red and if its in the future then it wont change. This works properly but it only changes state when I click on another button. I am using a ternary operator like this:
color: (run(todoController.todos[index].date,
todoController.todos[index].time)
.compareTo(tz.TZDateTime.now(tz.local))>0)
? Theme.of(context).hintColor
: Colors.redAccent,
How do you add setState in a ternary operator? Thanks
I think the neater solution would be moving the logic of the comparison of time in a separate function which will be called each 2/5 second depending on your app. In that function, you can change the state and make sure to use color depending on the state.
The code for checking the future time each minute
var cron = new Cron();
cron.schedule(new Schedule.parse('*/3 * * * *'), () async {
if(run(todoController.todos[index].date,
todoController.todos[index].time)
.compareTo(tz.TZDateTime.now(tz.local))>0){
setState(() {
isFutureTime = true;
});
}
});
I have used corn. CORN documentation
Your Widget color code would look like this.
isFutureTime == false? Theme.of(context).hintColor : Colors.redAccent,
isFutureTime is the state boolean variable. You can follow this StackOverflow answer on changing the state periodically.

Flutter Listview - Subtitle and DateDiff problem

i need your help :)
I think this is not working... but i mean i can do it with an extra page like a "detailpage" and show the data. Well here is my issue
i have the main screen with a listview.Builder for all my entries.
it just shows an icon, the title(name) and a Date (the Date is in the future that i can define in the add screen)
ok now my problem. i need a Datediff. i dont want to show the future Date (endTime), i want the differnce days between today and the future Date
child: ListTile(
leading: CircleAvatar(
backgroundImage:
AssetImage('asset/veggi.png'), ),
title: Text(vegetableEntry.items[index].title),
onTap: () => Navigator.of(context).pushNamed(vegetableDetailScreen.routeName,
arguments: vegetableEntry.items[index].id),
subtitle: Text(vegetableEntry.items[index].endTime.difference(dateNow2).inDays),
somtehing like:
that i get on my subtitle smth like: Icon/ Title(name) /DaysLeft: 29 (checks everytime on open?)
i'm getting the error:
The method 'difference' isn't defined for the type 'String'.
Try correcting the name to the name of an existing method, or defining a method named 'difference'.
i know i can fix it in the DetailScreen with
DateTime startDate = _pickedStartDate;
DateTime endDate = _pickedEndDate;
final daysLeft = endDate.difference(startDate).inDays;
print(daysLeft);
but i dont think this is possible in the Listview.builder ?
i hope this is understandable and someone can help me
best regards,
and a happy day :)
This actually is possible in ListView.builder. Just do the work in the builder function before you return the ListTile. You can't use (context, index) =>. You'll have to use (context, index) {}.
You can also convert the Timestamp String into a DateTime inline like so
subtitle: Text(DateTime.parse(vegetableEntry.items[index].endTime).difference(dateNow2).inDays.toString(),

Error: A value of type 'TimeOfDay' can't be assigned to a variable of type 'DateTime'

I am trying to get time from time picker in this format Thrusday at 10:00pm until. I did found a solution on google to use intl library from dart to format date to display in 10:00pm format. but here the problem is whenever i try to put DataTime.now() to get time picker I get this error.
Error: A value of type 'TimeOfDay' can't be assigned to a variable of type 'DateTime'.
Here is my code
DateTime _currentTime = new DateTime.now();
Future<Null> selectTime(BuildContext context) async {
DateTime seletedTime = await showTimePicker(context: context, initialTime: _currentTime);
}
Is there any way to get the time in 12 hour clock time something like this 10:00pm.
any help would be great.
You need to use:
TimeOfDay _currentTime = TimeOfDay.now();
Because, looking at the https://api.flutter.dev/flutter/material/showTimePicker.html, a TimeOfDay type is being used instead of DateTime.
You will need to change the call to the following to make everything work fine:
TimeOfDay selectedTime = await showTimePicker(context: context, initialTime: _currentTime);
Is there any way to get the time in 12 hour clock time something like this 10:00pm.
For your second question, you can use formatTimeOfDay from the MaterialLocalizations class. See the following:
https://api.flutter.dev/flutter/material/MaterialLocalizations/formatTimeOfDay.html
And set alwaysUse24HourFormat to false.
MaterialLocalizations localizations = MaterialLocalizations.of(context);
String formattedTime = localizations.formatTimeOfDay(selectedTime, alwaysUse24HourFormat: false);