how to calculate working hours from api data in flutter - flutter

i have fetched data from an api which contains employees working time,
i want to calculate total working hours each day
here's how i get the data from the api for 1 single day
Future<List> getPunchData(String empCode, DateTime date) async {
String ip = await confObj.readIp();
DateTime end = new DateTime(date.year, date.month, date.day, 23,59,59);
final response = await http.get(Uri.parse("url/$empCode&$date&$end" ));
final String t = response.body;
var jsonData =jsonDecode(t);
return jsonData;
}
the api result is this:
{
"id": 10,
"punch_time": "2022-03-08 13:30:19.000000",
},
{
"id": 11,
"punch_time": "2022-03-08 16:22:39.000000",
}..
..
..
how can i automatically calculate and isplay total hours when after the widget is loaded

You can use the parse function of the DateTime object to convert the String date into DateTime.
The code would somewhat look like this (can't say for sure as I don't know your API):
final DateTime startTime = DateTime.parse(jsonData[0]['punch_time']);
final DateTime endTime = DateTime.parse(jsonData[1]['punch_time']);
Once you have the DateTime object, you can use the difference function to get a Duration object which will tell you the hours an employee has worked.
final Duration durationWorked = startTime.difference(endTime);
final int hoursWorked = durationWorked.inHours;

Related

How do i compare current timestamp to the timestap from firebase flutter

I want to create a function which does not allow the user to remove the appointment once the timestamp for the appointment has past already. But what i tried below does not work, i hope to get some guidance from you guys
My widget.filter is a var which has the timestamp value from firebase
DateTime currentPhoneDate = DateTime.now(); //DateTime
Timestamp myTimeStamp = Timestamp.fromDate(currentPhoneDate); //To TimeStamp
DateTime myDateTime = myTimeStamp.toDate(); // TimeStamp to DateTime
print("current phone data is: $currentPhoneDate");
print("current phone data is: $myDateTime");
if(myTimeStamp < widget.filter){
print('work');
}else{
print('fail');
}
DateTime currentPhoneDate = DateTime.now();
Timestamp myTimeStamp = Timestamp.fromDate(currentPhoneDate);
DateTime myDateTime = myTimeStamp.toDate();
print("myTimeStamp is: $myTimeStamp");
print("currentPhoneDate is: $currentPhoneDate");
print("myDateTime is: $myDateTime");
// if widget.filter DataType is not Timestamp then first convert it to Timestamp.
if (myTimeStamp.millisecondsSinceEpoch <
widget.filter.millisecondsSinceEpoch) {
print('work');
} else {
print('fail');
}

flutter:: Is it possible to change the timezone of a datetime?

I want to represent the time the file was saved as a string. The time in my country is 9 hours ahead of utc time. How can I change the current utc time to 9 hours faster?
String _getTime({required String filePath}) {
String fromPath = filePath.substring(
filePath.lastIndexOf('/') + 1, filePath.lastIndexOf('.'));
if (fromPath.startsWith("1", 0)) {
DateTime dateTime =
DateTime.fromMillisecondsSinceEpoch(int.parse(fromPath));
var dateLocal = dateTime.toLocal();
print(dateLocal);
print(dateTime);
int year = dateLocal.year;
int month = dateLocal.month;
int day = dateLocal.day;
int hour = dateLocal.hour;
int min = dateLocal.minute;
String dato = '$year-$month-$day--$hour:$min';
return dato;
} else {
return "No Date";
}
}
Use this package ---->>>>> https://pub.dev/packages/flutter_native_timezone
Add the package dependencies to your project, import the package into the file you're working in and write the code below to get your currenTimeZone
final String currentTimeZone = await FlutterNativeTimezone.getLocalTimezone();
debugPrint(currentTimeZone);

How to implement Upcoming Date Countdown in flutter

I have a task to implement upcoming event date countdown. Example 1 months 2 days remaining. date is received from api like this 2021-10-18 17:00:00.000Z. I tried some examples but didn't got required output. Below is my implemented code
static String? dateDiff(String date){
if(date != "null") {
final date1 = DateTime.now().toUtc();
final DateTime date2 = DateTime.parse(date).toUtc();
final difference = date2.difference(date1).inDays;
print(difference); //
return difference.toString(); //
}
}
You can check the answer here out
Check here

How to get a list of each week in a time range with Dart?

I am trying to build a weeks-timeline in my Flutter app.
I am trying to generate a list of all of the weeks in a given time range (for example December 2020 - December 2021).
Each week will be a list by itself, which will hold the days. Something like this:
[
[
{
dayName: 'Sunday',
date: 'December 13 2020',
},
{
dayName: 'Monday',
date: 'December 14 2020',
},
{
dayName: 'Tuesday',
date: 'December 15 2020',
},
{
dayName: 'Wednesday',
date: 'December 16 2020',
},
{
dayName: 'Thursday',
date: 'December 17 2020',
},
{
dayName: 'Friday',
date: 'December 18 2020',
},
{
dayName: 'Saturday',
date: 'December 19 2020',
},
],
//Another Week Array
//Another Week Array
//Etc
]
Does anyone know how can I achieve this type of data in Dart and Flutter?
Thank you!
As Stefano wrote, it's good to create a class with a structure to be able to achieve your goals. My suggestion is a little more simple since I just wrote a method you could use. You could even create an extension on the DateTime class and use that in the future, or implement it in a static class, or add it to an instance class. Here is the complete example that works on DartPad:
void main() {
var weeks = getWeeksForRange(DateTime.utc(2020,08,12), DateTime.utc(2020,10,12));
print(weeks);
}
List<List<DateTime>> getWeeksForRange(DateTime start, DateTime end) {
var result = List<List<DateTime>>();
var date = start;
var week = List<DateTime>();
while(date.difference(end).inDays <= 0) {
// start new week on Monday
if (date.weekday == 1 && week.length > 0) {
print('Date $date is a Monday');
result.add(week);
week = List<DateTime>();
}
week.add(date);
date = date.add(const Duration(days: 1));
}
result.add(week);
return result;
}
This method can take any two dates and create a list of lists (weeks) of DateTime objects. Since in the result you will have many DateTime results, you can then map them however you want since they will have all information about its date, year, weekday and will keep the formatting feature.
One first step could be to create a Class according to your needs:
class Day {
final DateTime dateTime;
Day({
this.dateTime,
});
String get day => DateFormat('EEEE').format(dateTime);
String get date => DateFormat('yMMMd').format(dateTime);
Map<String, String> toMap() => {'dayName': day, 'date': date};
}
We can construct the Class above just with a DateTime and from it, we can derive the day and date using DateFormat in the getters:
String get day => DateFormat('EEEE').format(dateTime); // returns "Friday" for example
String get date => DateFormat('yMMMd').format(dateTime); // returns "Jun 13, 2021" for example
The toMap() method allows use to easily convert the Class to a Map<String, String>:
Map<String, String> toMap() => {'dayName': day, 'date': date};
We now need to store the Days in a List<Day>:
List<Day> days = [];
By iterating from the starting DateTime to the ending DateTime:
DateTime now = DateTime.now(); // as an example
DateTime start = now;
DateTime after = now.add(Duration(days: 180));
DateTime iterator = start;
List<Day> days = [];
while (iterator.isBefore(after)) {
days.add(Day(dateTime: iterator));
iterator = iterator.add(Duration(days: 1));
}
A full source code for the scenario outlined can be found below:
import 'package:intl/intl.dart';
class Day {
final DateTime dateTime;
Day({
this.dateTime,
});
String get day => DateFormat('EEEE').format(dateTime);
String get date => DateFormat('yMMMd').format(dateTime);
String toString() =>
'\t{\n\t\t"dayName": "$day",\n\t\t"date": "$date"\n\t}\n';
Map<String, String> toMap() => {'dayName': day, 'date': date};
}
void main() {
DateTime now = DateTime.now();
DateTime start = now;
DateTime after = now.add(Duration(days: 180));
DateTime iterator = start;
List<Day> days = [];
while (iterator.isBefore(after)) {
days.add(Day(dateTime: iterator));
iterator = iterator.add(Duration(days: 1));
}
print(days);
}
If you'd like to group the Days by week, we'll then need a multi-dimensional List:
void main() {
DateTime now = DateTime.now();
DateTime start = now;
DateTime after = now.add(Duration(days: 180));
DateTime iterator = start;
List<List<Day>> days = [[]]; // multi-dimensional List
int i = 0;
while (iterator.isBefore(after)) {
if (days[i].isEmpty) days.add([]); // init of the week List
days[i].add(Day(dateTime: iterator));
if (iterator.weekday == 7) i++; // new week
iterator = iterator.add(Duration(days: 1));
}
print(days);
}

convent and find The difference between date time flutter

I need to help with my fluter code,
I have an API its response me a date as a String
{"time": "12/04/2020 16:09:33"}
and I get the current time in my code from the phone using
var now = new DateTime.now();
how I can calculate the difference between two date-time???
You can use the intl library.
import 'package:intl/intl.dart';
String formatDuration(Duration duration) {
return duration.toString().split('.').first.padLeft(8, '0');
}
final s = "12/04/2020 16:09:33";
final formatter = DateFormat('dd/MM/yyyy HH:mm:ss');
final dateTime = formatter.parse(s);
var now = DateTime.now();
var difference = now.difference(dateTime);
print(formatDuration(difference));
print result ex. 53:37:11
You can achieve that using difference() method which accepts date as DateTime object. Hence, first you need to convert your input date which is in String format, into DateTime. Working code below:
String date = "12/04/2020 16:09:33";
DateFormat dateFormat = DateFormat("yyyy/MM/dd HH:mm:ss");
DateTime dateTime = dateFormat.parse(date); // converts into Datetime
var nowDate = DateTime.now();
var difference = nowDate.difference(dateTime);
print(difference); // 17553602:53:49.047936