Here is the Scala code to get start and end day of week dynamically.
Note:- Make sure start and end are in order for example when start day is Sunday
then Monday
is end day of week
def shiftWeeksBy(startDayOfWeek: Int, currentWeekDay: Int) : Int = (startDayOfWeek, currentWeekDay) match {
case (s, c) if s <= c | s == 1 => 0 //start day of week is Monday -OR- start day of week <= current week day
case _ => 1
}
def getStartAndEndDays(initialTime: DateTime, startDayOfWeek: Int, endDayOfWeek: Int): (Option[DateTime], Option[DateTime]) = {
val currentDateWeekDay = initialTime.dayOfWeek.get
(Some(initialTime.minusWeeks(shiftWeeksBy(startDayOfWeek, currentDateWeekDay)).withDayOfWeek(startDayOfWeek).withTimeAtStartOfDay()),
Some(initialTime.plusWeeks(shiftWeeksBy(currentDateWeekDay, endDayOfWeek)).withDayOfWeek(endDayOfWeek)))
}
Output:- For 5th Jan 2021
start day of week is Thursday
and end day of week is Wednesday
then week begins with 2020-12-31
and end with 2021-01-06
.
scala> getStartAndEndDays(new DateTime("2021-01-05T00:00:00.000"), 4, 3)
res5: (Option[org.joda.time.DateTime], Option[org.joda.time.DateTime]) = (Some(2020-12-31T00:00:00.000+05:30),Some(2021-01-06T00:00:00.000+05:30))