How to get the last Sunday before current date?

后端 未结 7 1200
花落未央
花落未央 2021-02-12 15:07

I have the following code for getting the last Sunday before the current date:

Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, cale         


        
7条回答
  •  北恋
    北恋 (楼主)
    2021-02-12 15:56

    Here's how to do it with a Kotlin extension and the Joda Time library.
    Answer is based on linqu's answer but this also fixes a bug in that answer. The bug was that it did not work if the current date was the same day you're trying to get.

    /**
     * E.g., DateTimeConstants.SUNDAY
     */
    fun DateTime.previousDayOfWeek(day: Int): DateTime {
        var date = this
        if(date.dayOfWeek == day) date = date.minusDays(1)
    
        val offset = (date.dayOfWeek - day + 7) % 7
        return date.minusDays(offset)
    }
    
    fun DateTime.previousSunday(): DateTime {
        return previousDayOfWeek(DateTimeConstants.SUNDAY)
    }
    

提交回复
热议问题