Jodatime start of day and end of day

I want to create an interval between the beginning of the week, and the end of the current week.

I have the following code, borrowed from this answer:

private LocalDateTime calcNextSunday(LocalDateTime d) {
    if (d.getDayOfWeek() > DateTimeConstants.SUNDAY) {
        d = d.plusWeeks(1);
    }
    return d.withDayOfWeek(DateTimeConstants.SUNDAY);
}

private LocalDateTime calcPreviousMonday(LocalDateTime d) {
    if (d.getDayOfWeek() < DateTimeConstants.MONDAY) {
        d = d.minusWeeks(1);
    }
    return d.withDayOfWeek(DateTimeConstants.MONDAY);
}

But now I want the Monday LocalDateTime to be at 00:00:00, and the Sunday LocalDateTime at 23:59:59. How would I do this?


Solution 1:

You can use the withTime method:

 d.withTime(0, 0, 0, 0);
 d.withTime(23, 59, 59, 999);

Same as Peter's answer, but shorter.

Solution 2:

also a simple way is

d.millisOfDay().withMaximumValue();

Solution 3:

How about:

private LocalDateTime calcNextSunday(LocalDateTime d) {
    return d.withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withDayOfWeek(DateTimeConstants.SUNDAY);
}

private LocalDateTime calcPreviousMonday(final LocalDateTime d) {
    return d.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withDayOfWeek(DateTimeConstants.MONDAY);
}

Solution 4:

With Kotlin you could write an extension function:

fun DateTime.withTimeAtEndOfDay() : DateTime = this.withTime(23,59,59,999)

This would allow you to write:

d.withDayOfWeek(DateTimeConstants.SUNDAY).withTimeAtEndOfDay()