Home > Blockchain >  Get startDate and endDate of week when pressing forward button or previous button
Get startDate and endDate of week when pressing forward button or previous button

Time:11-26

I am new to Kotlin. Which is the best way to get startDate and endDate of a week by pressing previous button to move one week backwards and next button to move one week forward? enter image description here

The text showing the dates defaults to the current week. I want when a user presses next to be able to update the text with the next week's start and end dates and vice versa when the user presses previous

CodePudding user response:

Here is example how to get startWeekDate.

private fun getStartWeekDate(){
    val cal = Calendar.getInstance()
    val currentDayOfWeek = cal.get(Calendar.DAY_OF_WEEK)
    val daysAfterSunday = currentDayOfWeek - Calendar.SUNDAY
    cal.add(Calendar.DATE, -daysAfterSunday)
    val theDateForSunday = cal.time
}

for the endDate()

private fun getEndWeekDate(){
    val cal = Calendar.getInstance()
    val currentDayOfWeek = cal.get(Calendar.DAY_OF_WEEK)
    val daysBeforeSaturday = currentDayOfWeek - Calendar.SATURDAY
    cal.add(Calendar.DATE, -daysBeforeSaturday)
    val theDateForSaturday = cal.time
}

CodePudding user response:

You did not mention which day of week is actually determining a start of an end of a week in your situation/culture/country.
That's why I can only come up with a fun that accepts a java.time.DayOfWeek as the only argument and calculates the next java.time.LocalDate with that DayOfWeek in the future. Fortunately, Kotlin provides the concept of extension functions, which means you can simply attach a new fun to LocalDate like this:

fun LocalDate.getNext(weekday: DayOfWeek): LocalDate {
    // add one day to have tomorrow
    var next = this.plusDays(1)
    // then start checking the days of week until the given one is reached
    while (next.dayOfWeek != weekday) next = next.plusDays(1)
    // when reached, return the result
    return next
}

You can use it in a main like this:

fun main() {
    val today = LocalDate.now()
    println("Today ($today) is ${today.dayOfWeek.getDisplayName(TextStyle.FULL, Locale.ENGLISH)}")
    val nextFriday = today.getNext(DayOfWeek.FRIDAY)
    println("Next Friday is $nextFriday")
    val nextMonday = today.getNext(DayOfWeek.MONDAY)
    println("Next Monday is $nextMonday")
}

This outputs

Today (2021-11-25) is Thursday
Next Friday is 2021-11-26
Next Monday is 2021-11-29

Ok, that's only half of your requirements, but I think you are able to write (nearly) the same method that gets you the most recent day of week instead of the upcoming one.

  • Related