Converting a List of DateTime into Strings - flutter

I'm trying to covert a list of dates into a string
var list = <DateTime>[];
DateTime start = DateTime(2019, 12, 01);
final end = DateTime(2021, 12, 31);
while (start.isBefore(end)) {
list.add(start);
start = start.add(const Duration(days: 1));
}
list.map((DateTime time) {
var dateRange = DateFormat("MM-dd-yy").format(time);
List<String> userSearchItems = [];
userSearchItems.add(dateRange);
print(userSearchItems);
});
but userSearchItems is coming up as empty

The code block inside list.map is never executed.
This is because list.map produces a lazy transformation of the list. The transformation function is executed only when elements are requested from it.
You probably want to use:
var dates = list.map((DateTime time) {
var dateRange = DateFormat("MM-dd-yy").format(time);
return dateRange;
});
print(dates);
In the code above, it is the print function that forces the transformation to run.
Alternatively, you can transform the result of the list.map to a list using
var datesList = dates.toList();
Again, this forces eager evaluation of the map transformation.

Related

How can I add working days to a specific date (Flutter)?

I want to add the calulated working days to a specific date.
For example
I want to add 14 working days
date -> 08.17.2022 (it is input)
newDate -> 09.06.20222 (it is output)
I tried it with the code below but it didn't work as I want. What is my wrong? How can I do that?
Thanks in advance.
final workingDays = <DateTime>[];
final currentDate = DateTime.fromMicrosecondsSinceEpoch(
widget.siparisModel.siparisTarih.microsecondsSinceEpoch);
final orderDate = currentDate.add(Duration(days: 15));
DateTime indexDate = currentDate;
while (indexDate.difference(orderDate).inDays != 0) {
final isWeekendDay = indexDate.weekday == DateTime.saturday || indexDate.weekday == DateTime.sunday;
if (!isWeekendDay) {
workingDays.add(indexDate);
}
indexDate = indexDate.add(Duration(days: 15));
}
You could do something like this:
var newDate = DateTime(2022, 08, 17); // Copy from some "currentDate"
var numOfWeekdaysToAdd = 14;
while (numOfWeekdaysToAdd > 0) {
do {
newDate = newDate.add(Duration(days: 1));
} while (newDate.weekday == DateTime.saturday || newDate.weekday == DateTime.sunday);
numOfWeekdaysToAdd--;
}
Working DartPad demo:
https://dartpad.dev/?id=6ef6f4306944b350edfb77905239297e
If you want to, you could extend the "weekend-check" and make it more complex to also check for holidays in a specific locale. In that case I'd have a list of holiday-dates, and just add something like holidayDates.contains(newDate)

how to calculate working hours from api data in 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;

Flutter convert string in list double

I have a response from REST API that return this:
var time = [{"duration":"00m 25s"},{"duration":"12m 08s"},{"duration":"02m 09s"},{"duration":"01m 25s"}, {"duration":"02m 05s"}]
I want to transform this list in:
var newTime = [0.25, 12.08, 2.09, 1.25, 2.05]
You can do string manipulation using splitting string using some delimiter like space and applying transformation via map.
void main() {
var time = [
{"duration": "00m 25s"},
{"duration": "12m 08s"},
{"duration": "02m 09s"},
{"duration": "01m 25s"},
{"duration": "02m 05s"}
];
time.map((e) {
final val = e['duration'].split(' '); // split by space
final result = val[0].substring(0, val[0].length - 1) + '.' +
val[1].substring(0, val[1].length - 1); // concat number by removing unit suffix
return double.tryParse(result); // parsing to double.
}).forEach((e) => print(e)); // 0.25, 12.08, 2.09, 1.25, 2.05
}
You can do it as follows:
var time = [{"duration":"00m 25s"},{"duration":"12m 08s"},{"duration":"02m 09s"},{"duration":"01m 25s"}, {"duration":"02m 05s"}];
var newList = time.map((time) {
String clippedMinutes; // will get the minutes part
String clippedSeconds; //// will get the seconds part
String fullTime = time['duration']; // full time part from each Map
final splittedTimeList = fullTime.split(' '); // splits the full time
clippedMinutes = splittedTimeList[0];
clippedSeconds = splittedTimeList[1];
return double.parse('${clippedMinutes.substring(0, clippedMinutes.length - 1)}.${clippedSeconds.substring(0, clippedSeconds.length - 1)}');
}).toList();
print(newList); // output: [0.25, 12.08, 2.09, 1.25, 2.05]
If it helped you don't forget to upvote
My contribution:
main(List<String> args) {
final times = [{"duration":"00m 25s"},{"duration":"12m 08s"},{"duration":"02m 09s"},{"duration":"01m 25s"}, {"duration":"02m 05s"}];
var regExp = RegExp(r'(\d\d)m (\d\d)s');
var newData = times.map((e) => double.parse(e['duration'].replaceAllMapped(regExp, (m) => '${m[1]}.${m[2]}')));
print(newData);
}
Result:
(0.25, 12.08, 2.09, 1.25, 2.05)

How to format date in list?

Is it possible to format a list of dates? I tried formatting it by formatting the list but got an error..
The argument type 'List' can't be assigned to the parameter type 'DateTime'.
var list = <DateTime>[];
DateTime start = DateTime(2018, 12, 30);
final end = DateTime(2022, 12, 31);
while (start.isBefore(end)) {
list.add(start);
start = start.add(const Duration(days: 1));
}
print(DateFormat("MM-dd-yyyy").format(list)); // The argument type 'List<DateTime>' can't be assigned to the parameter type 'DateTime'.
When I format the date before it's put in a list an error comes up saying you can't use isBefore on a string.
var list = <DateTime>[];
DateTime start = DateTime(2018, 12, 30);
var date = DateFormat("MM-dd-yyyy").format(start);
final end = DateTime(2022, 12, 31);
while (date.isBefore(end)) { //The method 'isBefore' isn't defined for the class 'String'.
list.add(start);
start = start.add(const Duration(days: 1));
}
Change the first code snippet to the following code:
var list = <String>[];
DateTime start = DateTime(2018, 12, 30);
final end = DateTime(2022, 12, 31);
while (start.isBefore(end)) {
var formatedData = DateFormat("MM-dd-yyyy").format(start)
list.add(formatedData);
start = start.add(const Duration(days: 1));
}
Since format() method returns a String then change the list to type String and then inside the while loop, you can format the start date and add it to the list.

Flutter how to get all the days of the week as string in the users locale

AS stated in the title: Is there an easy way to get all the days of the week as string(within a list ofcourse) in the users locale?
My suggestion is:
static List<String> getDaysOfWeek([String locale]) {
final now = DateTime.now();
final firstDayOfWeek = now.subtract(Duration(days: now.weekday - 1));
return List.generate(7, (index) => index)
.map((value) => DateFormat(DateFormat.WEEKDAY, locale)
.format(firstDayOfWeek.add(Duration(days: value))))
.toList();
}
The idea is we define the date of the first day in the current week depending on current week day. Then just do loop 7 times starting from calculated date, add 1 day on each iteration and collect the result of DateFormat().format method with pattern DateFormat.WEEKDAY. To increase performance you can use lazy initialization. For example:
/// Returns a list of week days
static List<String> _daysOfWeek;
static List<String> get daysOfWeek {
if (_daysOfWeek == null) {
_daysOfWeek = getDaysOfWeek(); // Here you can specify your locale
}
return _daysOfWeek;
}
Using the intl package, the easiest way I found would be:
import 'package:intl/intl.dart';
var days = DateFormat.EEEE(Platform.localeName).dateSymbols.STANDALONEWEEKDAYS;
print(days) // => ["Sunday", "Monday", ..., "Saturday"]
You can replace STANDALONEWEEKDAYS with WEEKDAYS to get the names as they would appear within a sentence (e.g. first letter lowercase in some languages).
Also, you may use SHORTWEEKDAYS and STANDALONESHORTWEEKDAYS respectively to get the weekday abbreviations. For even shorter abbreviations, use NARROWWEEKDAYS or STANDALONENARROWWEEKDAYS.
After doing:
import 'package:intl/date_symbol_data_local.dart';
String localeName = "pt_BR"; // "en_US" etc.
initializeDateFormatting(localeName);
Use this:
static List<String> weekDays(String localeName) {
DateFormat formatter = DateFormat(DateFormat.WEEKDAY, localeName);
return [DateTime(2000, 1, 3, 1), DateTime(2000, 1, 4, 1), DateTime(2000, 1, 5, 1),
DateTime(2000, 1, 6, 1), DateTime(2000, 1, 7, 1), DateTime(2000, 1, 8, 1),
DateTime(2000, 1, 9, 1)].map((day) => formatter.format(day)).toList();
}
I'm not sure it qualifies as "easy". Maybe someone here can come up with a better answer.
In case you need the current day or month localized with your phone settings
import 'dart:io';
import 'package:intl/date_symbol_data_local.dart';
final String defaultLocale = Platform.localeName; // Phone local
// String defaultLocale = "pt_BR"; // "en_US" etc. you can define yours as well
// add to init
#override
void initState() {
super.initState();
initializeDateFormatting(defaultLocale);
}
static String _getLocalizedWeekDay(String local, DateTime date) {
final formatter = DateFormat(DateFormat.WEEKDAY, local);
return formatter.format(date);
}
static String _getLocalizedMonth(String local, DateTime date) {
final formatter = DateFormat(DateFormat.MONTH, local);
return formatter.format(date);
}