Skip to content

Instantly share code, notes, and snippets.

@wverdese
Created July 6, 2017 12:19
Show Gist options
  • Save wverdese/ba712e792be73dee79da26a926090759 to your computer and use it in GitHub Desktop.
Save wverdese/ba712e792be73dee79da26a926090759 to your computer and use it in GitHub Desktop.
Week-Of-Year and Week-Based-Year for GroupBy for weeks
/* Turns out that DateTimeFormatter has a nice way of providing a value for grouping by elements with a LocalDate ordered by weeks.
* This works even when the week is split between December and January. Check out this method:
*/
public void test() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-ww");
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd-MM-yyyy");
for (int year = 2016; year >= 2015; year--) {
for (int month = 12; month >= 1; month = month - 11) {
for (int day = 31; day >= 1; day--) {
LocalDate localDate = LocalDate.of(year, month, day);
Log.d("Weeks", "week: " + formatter.format(localDate) + " at: "+ formatter2.format(localDate));
}
}
}
}
# As we can see from the output, the pattern "YYYY-ww" is perfect for the groupBy, because the last days of December will be "anticipated" to
# the week of the first week of the next year.
#
# week: 2016-02 at: 04-01-2016
# week: 2016-02 at: 03-01-2016
# week: 2016-01 at: 02-01-2016
# week: 2016-01 at: 01-01-2016
# week: 2016-01 at: 31-12-2015
# week: 2016-01 at: 30-12-2015
# week: 2016-01 at: 29-12-2015
# week: 2016-01 at: 28-12-2015
# week: 2016-01 at: 27-12-2015
# week: 2015-52 at: 26-12-2015
# week: 2015-52 at: 25-12-2015
/* Thus, an Rx Observable that wraps your query items into sections (emitted one by one) can be defined this way:
* final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-ww");
*/
public Observable<List<Item>> run() {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-ww");
return Observable.fromIterable(/* YOUR QUERY */)
.groupBy(item -> formatter.format(item.getDate()))
.flatMapSingle(Observable::toList);
//or map it to your section object
}
@philipphager
Copy link

philipphager commented Jul 18, 2017

Important Notice: This grouping is dependent on the locale of the user, which is implicitly used in the Formatter. The Locale.US for example would not output the above Date grouping, but would set i.e. 2016-53 instead of appending the days of the previous year to the first week of the new year. European locales are producing the desired output. In tests, we are setting the default locale to Locale.GERMANY to get the desired output, but it should be noticed that this grouping may vary across countries.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment