Reputation: 1848
I am creating an app where user can time in and time out, i want to add the functionality of calculating the total working hours. for example if time in value is 10:30 and time out value is 12:30 then total working hours should be 2.
please help how i can do this.
Update:
final DateTime checkInTime = DateTime.now().subtract(Duration(hours: 9, minutes: 10));
final DateTime checkOutTime = DateTime.now().subtract(Duration(hours: 5, minutes: 10));
final hours = checkOutTime.difference(checkInTime).inHours;
final minutes= checkOutTime.difference(checkInTime).inMinutes;
final totalWorkingHours = '$hours.${(minutes - (hours*60))} hrs';
print("hours "+totalWorkingHours); //output 4.0 hrs
it gives me 4 workinghours but it should have 6:0
Upvotes: 0
Views: 1458
Reputation: 3179
You can do that like this
void main() {
final DateTime checkInTime = DateTime.now().subtract(Duration(hours: 3));
final DateTime checkOutTime = DateTime.now();
final totalWorkingHours = checkOutTime.difference(checkInTime).inHours;
print(totalWorkingHours);
}
Output will be 3
The above code only handle the hours, but if you want to handle both hrs and minutes then use the below code
void main() {
final DateTime checkInTime = DateTime.now().subtract(Duration(hours: 3, minutes: 30));
final DateTime checkOutTime = DateTime.now();
final hours = checkOutTime.difference(checkInTime).inHours;
final minutes= checkOutTime.difference(checkInTime).inMinutes;
final totalWorkingHours = '$hours.${(minutes - (hours*60))} hrs';
print(totalWorkingHours);
}
Output will be 3.30 hrs
Upvotes: 1
Reputation: 437
You can do it with simple math i.e
time out - time in = total working hours
Let's break down how to solve this in flutter
In
in DateTime i.e DateTime.now()Out
code will look like
DateTime inTime = populateYourInTimeHere();
DateTime outTime = poupulateYourOutTimeHere();
Duration workingHours = outTime.difference(inTime);// main part you need to know
format(Duration d) => d.toString().split('.').first.padLeft(8, "0");
The total working hour is format(workingHours)
Upvotes: 1