How to sort TimeOfDay list from earliest to latest time? - flutter

I need to display a schedule for users that displays times from earliest to latest time. I have a TimeOfDay list containing times and need it to be sorted from earliest to latest time. I made a function for it, but keep getting _TypeError (type 'TimeOfDay' is not a subtype of type 'String') when I run my code. Since I utilize the function inside a Column in my Widget build code block, I think it has to return a widget. Please let me know how I can resolve this error and efficiently sort my list through a function. The code for my function is below, any help would be appreciated!
listOrder(l) {
l.sort((a,b) => DateTime.parse(a).compareTo(DateTime.parse(b)));
return Text('Done!');
}

DateTime.parse expects a String input, not a TimeOfDay instance.
If you want to sort a List<TimeOfDay>, you need to provide a comparison function that compares TimeOfDay instances:
int compareTimeOfDay(TimeOfDay time1, TimeOfDay time2) {
var totalMinutes1 = time1.hour * 60 + time1.minute;
var totalMinutes2 = time2.hour * 60 + time2.minute;
return totalMinutes1.compareTo(totalMinutes2);
}
void main() {
var list = [
TimeOfDay(hour: 12, minute: 59),
TimeOfDay(hour: 2, minute: 3),
TimeOfDay(hour: 22, minute: 10),
TimeOfDay(hour: 9, minute: 30),
];
list.sort(compareTimeOfDay);
print(list);
}

i think you are missing return value form sort method. since you are using curly brackets,
here i try on dartpad is working fine
void main() {
List date = ['2022-02-02','2022-02-15','2022-02-01'];
date.sort((a,b) => DateTime.parse(a).compareTo(DateTime.parse(b)));
print(date); //result : [2022-02-01, 2022-02-02, 2022-02-15]
}
if you have 1 argument, you can simplify with arrow => , but if you have more than 1, use brackets {}
l.sort((a,b){
return DateTime.parse(a).compareTo(DateTime.parse(b)); // see i add a return syntax
});

Related

Convert .toString() to Timestamp object

Anyone know how to convert string "Timestamp(second=16698..., nanoseconds=187...)" from Google Firestore to a Dart Timestamp object?
I couldn't find anything with this particular example
I made this function, adjust it to suit your case
customTimeStamp(String strSeconds) {
final seconds = strSeconds.substring(
strSeconds.indexOf('=') + 1, strSeconds.indexOf(','));
final nanoSeconds = strSeconds.substring(
strSeconds.lastIndexOf('=') + 1, strSeconds.indexOf(')'));
return Timestamp(
int.tryParse(seconds) ?? 0, int.tryParse(nanoSeconds) ?? 0);
}

How can i increase only 1 microsecond to DateTime.now() in dart

i have the following
Dateime.now() + here i need to increase only 1 microsecond
so wanted output is Dateime.now() + that incensement which is 1 microsecond
i tried the following but it does not work
print(DateTime.now()+const Duration(microsecond : 1);)
How can i implement this
This well get it done.
final now = DateTime.now();
final later = now.add(const Duration(millisecond: 1));
check docs here
Or do it in a single line:
DateTime now = DateTime.now().add(Duration(milliseconds: 1));
print(now);
DateTime does not define an operator +, but it does have an add method that accepts a Duration. (You also have a couple of syntax errors in your code; the semicolon is misplaced, and the named parameter to Duration is microseconds, not microsecond.)
If you're testing with Dart for the Web (such as with DartPad), you will not get microsecond precision due to limitations with JavaScript. Running the following code in the Dart VM will show a change in microseconds:
void main() {
var now = DateTime.now();
const microsecond = Duration(microseconds: 1);
print(now); // Prints: 2022-04-23 20:39:28.295803
print(now.add(microsecond)); // Prints: 2022-04-23 20:39:28.295804
}
Also see: https://stackoverflow.com/a/60747710/

Flutter how to subtract time from other time

I have 2 times which I need to do subtract and I am almost close but there is one big issue
I have 2 times in string-like 10:00AM and 10:00PM
And my code is this
var df = DateFormat("hh:mm");
var durationStart = DateFormat('HH:mm').format(df.parse(10:00AM));
var durationEnd = DateFormat('HH:mm').format(df.parse(10:00PM));
print('durationStart ${durationStart}');
print('durationEnd ${durationEnd}');
var Startparts = durationStart.split(':');
var startDurationSet = Duration(hours: int.parse(Startparts[0].trim()), minutes: int.parse(Startparts[1].trim()));
var Endparts = durationEnd.split(':');
var endDurationSet = Duration(hours: int.parse(Endparts[0].trim()), minutes: int.parse(Endparts[1].trim()));
print('startDurationSet ${startDurationSet}');
var result = Duration(hours: int.parse(Endparts[0].trim()) - int.parse(Startparts[0].trim()) , minutes: int.parse(Startparts[1].trim()) - int.parse(Endparts[1].trim()));
print('result ${result.toString().replaceAll('-', '')}');
So I have 2 times one is startTime and one is End time. I simply need a difference between hours. for example, I have 10:00Am and 01:00PM i need 3hours but it's showing 9hours. But what I am receiving is if I have 10:00AM and 10:00pm it's showing 0 hours but its needs to show 12. Same
It is easy if you can get your start and end date in DateTime properly
Hint, I use "hh:mma" since that is your original format => "10:00AM"
If I use "HH:mm" like you do, i'll always get the same time since it doesn't parse the AM/PM after the 10:00
// Get your time in term of date time
DateTime startDate = DateFormat("hh:mma").parse("10:00AM");
DateTime endDate = DateFormat("hh:mma").parse("10:00PM");
// Get the Duration using the diferrence method
Duration dif = endDate.difference(startDate);
// Print the result in any format you want
print(dif.toString(); // 12:00:00.000000
print(dif.inHours); // 12
Are you looking for something like this?
TimeOfDay _calcTimeOfDay(int hour, int minute) {
if (minute > 60) {
minute = (minute % 60);
hour += 1;
}
return TimeOfDay(hour: hour, minute: minute);
}
The problem is if you have hour=24 and minute=75 then the hour would be 25, which is not a valid hour.
Not sure I fully understand the question, maybe if you can provide more info.
What you need to add on your DateFormat is the code for am/pm marker: a. Using either format hh:mma or h:ma should work.
You can then use DateTime.difference() to calculate the time variance from durationStart and durationEnd. Here's a sample that you can run on DartPad.
import 'package:intl/intl.dart';
void main() {
/// Set the format that of the Date/Time that like to parse
/// h - 12h in am/pm
/// m - minute in hour
/// a - am/pm marker
/// See more format here: https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html
var dateFormat = DateFormat('h:ma');
DateTime durationStart = dateFormat.parse('10:00AM');
DateTime durationEnd = dateFormat.parse('10:00PM');
print('durationStart: $durationStart');
print('durationEnd: $durationEnd');
/// Fetch the difference using DateTime.difference()
/// https://api.flutter.dev/flutter/dart-core/DateTime/difference.html
print('difference: ${durationEnd.difference(durationStart).inHours}');
}
Use package
intl: ^0.17.0
import 'package:intl/intl.dart';
var dateFormat = DateFormat('h:ma');
DateTime durationStart = dateFormat.parse('10:00AM');
DateTime durationEnd = dateFormat.parse('1:00PM');
print('durationStart: $durationStart');
print('durationEnd: $durationEnd');
var differenceInHours = durationEnd.difference(durationStart).inHours;
print('difference: $differenceInHours hours');
I have created one class for you:
import 'package:intl/intl.dart';
class DateUtils {
static String getTimeDifference(String startTime, String endTime){
/// Set the format that of the Date/Time that like to parse
/// h - 12h in am/pm
/// m - minute in hour
/// a - am/pm marker
/// See more format here: https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html
var dateFormat = DateFormat('h:ma');
DateTime durationStart = dateFormat.parse(startTime);
DateTime durationEnd = dateFormat.parse(endTime);
return '${durationEnd.difference(durationStart).inHours} hours';
}
}
How you can use:
void main() {
print("10:00PM, 10:30PM => " + DateUtils.getTimeDifference("10:00PM", "10:30PM"));
print("12:00AM, 04:00AM => " + DateUtils.getTimeDifference("12:00AM", "04:00AM"));
print("01:00AM, 03:00AM => " + DateUtils.getTimeDifference("01:00AM", "03:00AM"));
print("12:00AM, 06:00PM => " + DateUtils.getTimeDifference("12:00AM", "06:00PM"));
print("04:00PM, 03:00PM => " + DateUtils.getTimeDifference("04:00PM", "03:00PM"));
}
Output:
10:00PM, 10:30PM => 0 hours
12:00AM, 04:00AM => 4 hours
01:00AM, 03:00AM => 2 hours
12:00AM, 06:00PM => 18 hours
04:00PM, 03:00PM => -1 hours
Hope it will be helpful.

Get the next immediate Time from a list of date time in dart

If I have a list of DateTime =
[
2021-08-17 11:00:00.000000,
2021-08-17 11:30:00.000000,
2021-08-17 12:00:00.000000,
2021-08-17 12:30:00.000000,
2021-08-17 13:00:00.000000,
]
How can I find the immediate next TIME using DateTime.now()?
ONLY TIME.
If DateTime.now() returns 2021-08-17 11:25:00.000000 I need to return 5 minutes
**CONTEXT: **
My application needs to save the DateTime for another work so I cannot just save the Time. The above mentioned list of DateTimes is saved under the title: Sunday. Checking if today is Sunday or not is quite easy but I need some sort of mechanism for getting the difference with next datetime but I only need the Time difference and not the date
Assuming that your List<DateTime> is sorted in order of earliest to latest, a straightforward, brute-force approach is to just iterate over your List<DateTime> and stop when you find one that is at or after the specified DateTime:
/// Returns the [Duration] to the next [DateTime] from [validTimes] that occurs at
/// or after [now].
///
/// Returns `null` if there is no [DateTime] at or after [now].
///
/// [validTimes] must be already sorted in order of earliest to latest.
Duration? timeToNext(List<DateTime> validTimes, DateTime now) {
for (var time in validTimes) {
if (time.compareTo(now) >= 0) {
return time.difference(now);
}
}
return null;
}
void main() {
var times = [
DateTime(2021, 08, 17, 11, 00),
DateTime(2021, 08, 17, 11, 30),
DateTime(2021, 08, 17, 12, 00),
DateTime(2021, 08, 17, 12, 30),
DateTime(2021, 08, 17, 13, 00),
];
var now = DateTime(2021, 08, 17, 11, 25);
var duration = timeToNext(times, now);
print(duration); // Prints: 0:05:00.000000
}
If your List<DateTime> is very large, then you could use lowerBound from package:collection:
import 'package:collection/collection.dart';
Duration? timeToNext(List<DateTime> validTimes, DateTime now) {
var i = lowerBound(validTimes, now);
if (i == validTimes.length) {
return null;
}
return validTimes[i].difference(now);
}
If i understood correctly,
the difference between DateTimes is pretty easy using difference method for the DateTime class look that in action:
int returnDiference(DateTime dateTime1, DateTime dateTime2) {
final int diference = dateTime1.difference(dateTime2).inSeconds;
return diference;
}
enter image description here
I hope that will be useful for you.

How to store dates in a List<DateTime> in flutter?

I am trying to use a PageView.builder in my application and i wanted each page to display a particular date. I have defined a list of type DateTime : List<DateTime> _month;. how do i store all the days in a particular month (30 days) in the list _month?
The stored dates must be of type DateTime in order to implement this in my application.
This code will do what you need. I don't know the entire structure of your code so I just wrote this example!
void main() {
int month = 1;
DateTime start = DateTime(2019,month);
DateTime end = DateTime(2019,month+1);
int c = (end.toUtc().difference(start.toUtc()).inDays);
List<DateTime> _month = [];
_month.addAll(List.generate(c,(index) => start.toUtc().add(Duration(days:index)).toLocal()));
print(_month);
}