How to Sort List of Week Day names in flutter in ascending order - flutter

I have a list of Week Day names in random order, how to sort it in ascending order e.g. Monday, Tuesday, Wednesday …
List
[Friday, Monday, Sunday, Wednesday]
Desired List
[Monday, Wednesday, Friday, Sunday]
I have tried
list.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));

The issue you're going to have to overcome is that there is no super easy way to get a listing of the days of the week. However, that isn't actually a difficult issue to deal with if you're only needing to deal with this for english - you can just hardcode it.
Here's an example:
const weekDays = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
];
final positions = weekDays.asMap().map((ind, day) => MapEntry(day, ind));
The positions is slightly more interesting; by calling asMap, I'm converting the list to a map with the keys being the positions (i.e. 0:"Monday", ... 6:"Friday") and then swapping them. This will result in a slightly faster lookup than just using indexOf, although that's realistically probably an unnecessary optimization in this case.
Then to sort, you can just use a list's sort method and pass it a custom comparitor function:
dates.sort((first, second) {
final firstPos = positions[first] ?? 7;
final secondPos = positions[second] ?? 7;
return firstPos.compareTo(secondPos);
});
Putting it all together, this is what it looks like:
const weekDays = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
];
final positions = weekDays.asMap().map((ind, day) => MapEntry(day, ind));
void main() {
final dates = ["Friday", "Monday", "Sunday", "Banana", "Wednesday"];
dates.sort((first, second) {
final firstPos = positions[first] ?? 8;
final secondPos = positions[second] ?? 8;
return firstPos.compareTo(secondPos);
});
print("sorted: $dates");
}
Note that if your data isn't complete sanitized, you might want to normalize it to be all lower case, and do the same for your "weekDays" listing.

To sort the list of days such that it starts from Sunday in ascending order, you can use the sort method from the List class and specify a custom Comparator function that compares the days based on their index in the list. The code for this will be:
https://gist.github.com/tanmoy27112000/f0077c593dd883d93a338261fd9a96a5
This will compare the days provided with the given dayList and give you the required sorted list.
sortedDays can also be modified to sort the given list according to your liking.

you can add mapping data with value ex
const map = { 'Monday': 1, 'Tuesday': 2, 'Wednesday': 3, 'Thursday': 4, 'Friday': 5, 'Saturday': 6, 'Sunday': 7 };
and then you can mapping value and sort it. or you can see in this ask
link

Related

How to reduce a list to earliest/latest DateTime items in Dart- you know the fun type of code problem

I have a list of DateTime items, I want to get the earliest and latest items in that list for initializing a date range picker with min/max values based on the available data in db.
I have a tough time tracking the "behind the scenes" in loops and the reduce operator. So I'm looking for any help in making this happen efficiently, cause I'm sure I can make this happen inefficiently with 10 loops :P
What I've tried so far, random stuff that obviously is way off. Double loops and looping with reduce and .isbefore or .isAfter. Can't figure this out. My code below is a hodgepodge but it's where I'm at now. I guess another option is to simple order the list by date and take first and last, but I want to see the best solution and I think this is the right place to ask.
This is what I'm trying to apply.
List<DateTime> dateList = [
DateTime(2021, 7, 30),
DateTime(2021, 6, 25),
DateTime(2021, 5, 14),
DateTime(2021, 4, 2),
DateTime(2021, 3, 12),
DateTime(2021, 3, 21)
];
List<DateTime> databaseDateRange() {
var databaseDateRange = <DateTime>[];
for (var item in dateList) {
dateList.reduce((value, element) {
if (value.isAfter(item)) {
databaseDateRange.add(value.xAxis);
}
});
}
return databaseDateRange;
}
print(dateList.reduce((min, e) => e.isBefore(min)? e : min));
In order to get the minimum in the list (i.e earliest date) you can do as #the38amorim said.
I.e
print(dateList.reduce((min, e) => e.isBefore(min) ? e : min));
The above iterates through each one and checks whether the new value is before the saved one, and replaces it if that is the case, otherwise keeps the old one.
For maximum value in the list (i.e latest date), you can conversely do:
print(dateList.reduce((min, e) => e.isAfter(min) ? e : min));
More on reduce here: https://api.dart.dev/stable/2.18.1/dart-core/Iterable/reduce.html

Dart, Compareto two situations in same time on list items

I have formatted dateFormat items, I mean : 11-08, 22-12 "dd-MM" items in a list. I want to sort them from the nearest date to farthest date. I did use compareTo like that (tumKisiler is a list)
'''
tumKisiler.sort((a, b) {
return a.siralamaDogumTarihi
.substring(3, 5)
.compareTo(b.siralamaDogumTarihi.substring(3, 5));
'''
but that is only sort by months. I want to sort by days also.
The output must be look like that :
13-08
26-08
17-09
31-12
How can I do that? I am new here, I hope could explain.

Format date into a month count and years

We have a DateTime value returning from JSON its coming thru as "10/9/2016 4:46:48 PM" .
What we need to do with it is format it to months or years past like so:
10/9/2016 = 3 years in the past.
The value 10/20/2019 = 3 months
Is this possible?
I'm guessing we would need to grab the month and year and subtract from today's date.
So I would create a function which will calculate difference between today's date and DateTime passed to it. It would look like this
String calculateDifference(DateTime dateTime) {
String text = "months";
double difference = DateTime.now().difference(dateTime).inDays / 30;
if (difference > 11) {
difference = difference / 12;
text = "years";
}
return "${difference.toStringAsFixed(0)} $text";
}
So you just need to parse the date from your JSON to DateTime object and pass it to a variable. You can also add one more condition to return value for days
You can use .difference on DateTime
final dateInThePast = DateTime(2018, 1, 7);
final dateNow = DateTime.now();
final difference = dateNow.difference(dateInThePast).inDays;
And then calculate from Days to Months / Years

Scala : exclude some Dates

I have a list of dates that i want to ignore :
private val excludeDates = List(
new DateTime("2015-07-17"),
new DateTime("2015-07-20"),
new DateTime("2015-07-23")
)
But i always need to display four dates excluding my black Dates list and the weekends. So far with the following code, my counter is increased when i hit an ignored date and it make sens. So how i can jump to the next date until i hit 4 dates not in my black list and my Weekends ? Maybe with a while, but i dont know how to add it in my scala code :
1 to 4 map { endDate.minusDays(_)} diff excludeDates filter {
_.getDayOfWeek() match {
case DateTimeConstants.SUNDAY | DateTimeConstants.SATURDAY => false
case _ => true
}
}
You could use a Stream :
val blacklist = excludeDates.toSet
Stream.from(1)
.map(endDate.minusDays(_))
.filter(dt => ! blacklist.contains(dt))
.take(4)
.toList
In a quick and rough way I would do it like this
val upperLimit = 4 + excludeDates.length
(1 to upperLimit).map( endDate.minusDays ).filter( d => !excludeDates.contains(d) ).take(4)
In short you go from the end date backward at max the number of dates you need plus the size of the excluded dates, then you filter the sequence checking if the date is not the excluded list and finally you pick only the dates you need with .take( n )
Hope it helps :)

nvd3 (d3.js) date format returns incorrect month

My data looks like this:
[{ x="2013-06-01", y=3}, { x="2013-07-01", y=7 }, { x="2013-08-01", y=3 }]
Chart x-axis is formatted as so:
chart.xAxis
.axisLabel('Date')
.tickFormat(function(d) { return d3.time.format('%b %Y')(new Date(d)); })
;
%b returns May, Jun, July respectively for the dates 2013-06-01, 2013-07-01, 2013-08-01
Why is it returning the previous month, and how can I fix it?
EDIT: If the date is formatted as 2013-06-02, it will return the correct month... does someone know what is happening to cause this?
#Amelia is correct it's because of timezone difference and because Date defaults to 24:00:00 if you don't specify a time. So, in case of EDT, which is -4:00, you lose 4 hours which puts you in the previous day (May 31 2013 20:00:00) and because the days in your dates are 01, this puts you in the previous month.
To bypass this you could append a time to your date if that is allowable in your case.
chart.xAxis
.axisLabel('Date')
.tickFormat(function(d) {
d = d.split('-')
// Create new date by using new Date(year, month, day, hour, second, ms)
// Subtracting 1 is necessary since Javascript months are 0 - 11.
return d3.time.format('%b %Y')(new Date(d[0], +d[1] - 1, d[2], 12, 0, 0));
});
Here is a working Fiddle