简体   繁体   中英

How to get first & last day of current week/month

I had a requirement where I need to get the first & last day of the week/month and also can change the week/month to next or previous week/month

Use this Utils which use joda-time lib

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)
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM