如何获取当前周/月的第一天和最后一天

时间:2021-02-11 11:39:16

标签: android datetime kotlin

我有一个要求,我需要获取一周/月的第一天和最后一天,并且还可以将周/月更改为下一周或上一周/月

1 个答案:

答案 0 :(得分:2)

使用这个使用 joda-time 库的实用程序

DateUtils.kt

import org.joda.time.DateTime
import org.joda.time.DateTimeConstants
import org.joda.time.format.DateTimeFormat

object DateUtils {

fun getCurrentWeekStartEndDate(): StartEndDate {
    return StartEndDate(
            DateTime.now().withDayOfWeek(DateTimeConstants.SUNDAY).minusWeeks(1),
            DateTime.now().withDayOfWeek(DateTimeConstants.SATURDAY)
    )
}

fun getNextWeekStartEndDateTime(currentDate: DateTime): StartEndDate {
    return StartEndDate(
            currentDate.withDayOfWeek(DateTimeConstants.SUNDAY),
            currentDate.withDayOfWeek(DateTimeConstants.SATURDAY).plusWeeks(1)
    )
}

fun getPreviousWeekStartEndDateTime(currentDate: DateTime): StartEndDate {
    return StartEndDate(
        currentDate.withDayOfWeek(DateTimeConstants.SUNDAY).minusWeeks(1),
        currentDate.withDayOfWeek(DateTimeConstants.SATURDAY)
    )
}

fun getCurrentMonthStartEndDate(): StartEndDate {
    return StartEndDate(
            DateTime.now().dayOfMonth().withMinimumValue(),
            DateTime.now().dayOfMonth().withMaximumValue()
    )
}

fun getNextMonthStartEndDateTime(currentDate: DateTime): StartEndDate {
    return StartEndDate(
            currentDate.plusMonths(1).dayOfMonth().withMinimumValue(),
            currentDate.plusMonths(1).dayOfMonth().withMaximumValue()
    )
}

fun getPreviousMonthStartEndDateTime(currentDate: DateTime): StartEndDate {
    return StartEndDate(
        currentDate.minusMonths(1).dayOfMonth().withMinimumValue(),
        currentDate.minusMonths(1).dayOfMonth().withMaximumValue()
    )
}

data class StartEndDate(val startDate: DateTime, val endDate: DateTime)

fun DateTime.toDefaultDateTimeString(dateTimeFormat: String) : String {
    return DateTimeFormat.forPattern(dateTimeFormat).print(this)
}
}