Last active
May 22, 2022 05:26
-
-
Save uzilan/add151b15fb0029fec7ba8cff58ad73a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package calendarish; | |
import java.time.DayOfWeek; | |
import java.time.Duration; | |
import java.time.LocalDate; | |
import java.time.Month; | |
import java.time.ZoneId; | |
import java.time.temporal.ChronoField; | |
import java.time.temporal.WeekFields; | |
import java.util.Calendar; | |
import java.util.GregorianCalendar; | |
import java.util.List; | |
import java.util.stream.Stream; | |
public class Calendarish { | |
interface Strategy { | |
int getWeek(final LocalDate date); | |
} | |
private List<Integer> weeksBetween( | |
final LocalDate startDate, | |
final LocalDate endDate, | |
final Strategy strategy) { | |
final long durationInDays = Duration.between( | |
startDate.atStartOfDay(), | |
endDate.atStartOfDay()).toDays(); | |
return Stream.iterate(startDate, date -> date.plusDays(1)) | |
.limit(durationInDays) | |
.map(strategy::getWeek) | |
.distinct() | |
.toList(); | |
} | |
public static void main(String[] args) { | |
final var startDate = LocalDate.of(2022, Month.FEBRUARY, 1); | |
final var endDate = LocalDate.of(2022, Month.FEBRUARY, 13); | |
final Strategy theGoodOldWay = date -> GregorianCalendar | |
.from(date.atStartOfDay(ZoneId.systemDefault())) | |
.get(Calendar.WEEK_OF_YEAR); | |
final Strategy theISOWay = date -> date.get(WeekFields.ISO.weekOfYear()); | |
final Strategy theAlignedWay = date -> | |
date.get(ChronoField.ALIGNED_WEEK_OF_YEAR); | |
final var broadcastCalendar = WeekFields.of(DayOfWeek.MONDAY, 1); | |
final Strategy theBroadcastWay = date -> | |
date.get(broadcastCalendar.weekOfYear()); | |
final var calendarish = new Calendarish(); | |
System.out.println("The good old way: " | |
+ calendarish.weeksBetween(startDate, endDate, theGoodOldWay)); | |
System.out.println("The ISO way: " | |
+ calendarish.weeksBetween(startDate, endDate, theISOWay)); | |
System.out.println("The aligned way: " | |
+ calendarish.weeksBetween(startDate, endDate, theAlignedWay)); | |
System.out.println("The broadcast way: " | |
+ calendarish.weeksBetween(startDate, endDate, theBroadcastWay)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment