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

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/

Related

How to sort TimeOfDay list from earliest to latest time?

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
});

How to get difference between 1 Timestamp and 1 dateTime in minute or day

using DateTime we can use the following to get the difference
DateTime myFirstDateTime = DateTime.now();
DateTime mySecondtDateTime = DateTime.now();
myFirstDateTime.difference(mySecondtDateTime).inMinutes // or inDay
the previous code is working as expected but how can I handle the same between Timestamp and DateTime ?
I used the following but it give wrong result and strange negative numbers like -5623
Timestamp myTimestamp = // here I get the value from my Firebase field
DateTime myDateTime = DateTime.now();
then I convert it `toDate()`
myDateTime.difference(myTimestamp.toDate()).inMinutes; //or inDay
//output strange value
How can I do it? Thanks
You might have to move the brackets as follows:
myDateTime.difference(myTimestamp.toDate()).inMinutes;
Try this one out
var myTimestamp = // here you get the value from your Firebase field
DateTime myDateTime = DateTime.now();
DateTime myFirebaseTime = DateTime.parse(myTimestamp.toDate().toString());
myDateTime.difference(myFirebaseTime).inDays;

Time with flutter

I am totally new with flutter and I do not understand how can I resolve a problem.
I'm actually working to a kart race app and:
I need to read a string like 1:02.456
Convert in some kind of time
Compare with another string similar to first one
Go to do something
es:
blap = null;
if(1:02.456 < 1:03.589){
blap = '1:02.456';
} else {
blap = '1:03.589;
}
I read on the web that I ca use the class DateTime, but every time I try to convert the string in an object of that class, I do not get wat I want.
There is a better way?
Thank you.
If you are working on a kart race app probably you need to use Duration, not DateTime.
This is one way to convert a string like yours into Duration
Duration parseDuration(String s) {
int hours = 0;
int minutes = 0;
int micros;
List<String> parts = s.split(':');
if (parts.length > 2) {
hours = int.parse(parts[parts.length - 3]);
}
if (parts.length > 1) {
minutes = int.parse(parts[parts.length - 2]);
}
micros = (double.parse(parts[parts.length - 1]) * 1000000).round();
return Duration(hours: hours, minutes: minutes, microseconds: micros);
}
Then, to compare two Duration in the way you wanted, this is an example:
String blap;
Duration time1=Duration(hours: 1),time2=Duration(hours: 2);
if(time1.compareTo(time2)<0){
//time2 is greater than time1
blap=time1.toString();
}else{
blap=time2.toString();
}

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.

Comparing only dates of DateTimes in Dart

I need to store and compare dates (without times) in my app, without caring about time zones.
I can see three solutions to this:
(date1.year == date2.year && date1.month == date2.month && date1.day == date2.day)
This is what I'm doing now, but it's horrible verbose.
date1.format("YYYYMMDD") == date2.format("YYYYMMDD")
This is still rather verbose (though not as bad), but just seems inefficient to me...
Create a new Date class myself, perhaps storing the date as a "YYYYMMDD" string, or number of days since Jan 1 1980. But this means re-implementing a whole bunch of complex logic like different month lengths, adding/subtracting and leap years.
Creating a new class also avoids an edge case I'm worried about, where adding Duration(days: 1) ends up with the same date due to daylight saving changes. But there are probably edge cases with this method I'm not thinking of...
Which is the best of these solutions, or is there an even better solution I haven't thought of?
Since I asked this, extension methods have been released in Dart. I would now implement option 1 as an extension method:
extension DateOnlyCompare on DateTime {
bool isSameDate(DateTime other) {
return year == other.year && month == other.month
&& day == other.day;
}
}
You can use compareTo:
var temp = DateTime.now().toUtc();
var d1 = DateTime.utc(temp.year,temp.month,temp.day);
var d2 = DateTime.utc(2018,10,25); //you can add today's date here
if(d2.compareTo(d1)==0){
print('true');
}else{
print('false');
}
DateTime dateTime = DateTime.now();
DateTime _pickedDate = // Some other DateTime instance
dateTime.difference(_pickedDate).inDays == 0 // <- this results to true or false
Because difference() method of DateTime return results as Duration() object, we can simply compare days only by converting Duration into days using inDays property
The easiest option is just to use DateUtils
For example
if (DateUtils.isSameDay(date1, date2){
print('same day')
}
isSameDay takes in 2 DateTime objects and ignores the time element
I am using this function to calculate the difference in days.
Comparing dates is tricky as the result depends not just on the timestamps but also the timezone of the user.
int diffInDays (DateTime date1, DateTime date2) {
return ((date1.difference(date2) - Duration(hours: date1.hour) + Duration(hours: date2.hour)).inHours / 24).round();
}
Use instead the package: dart_date
Dart Extensions for DartTime
dart_date provides the most comprehensive, yet simple and consistent toolset for manipulating Dart dates.
dart_date
DateTime now = DateTime.now();
DateTime date = ....;
if (date.isSameDay(now)) {
//....
} else {
//....
}
Also here the difference in days :
int differenceInDays(DateTime a, DateTime b) => a.differenceInDays(b);
Use isAtSameMomentAs:
var date1 = DateTime.now();
var date2 = date1.add(Duration(seconds: 1));
var isSame = date1.isAtSameMomentAs(date2); // false