Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a DateTime corresponding to next occurence of hour, minute?

Tags:

jodatime

I'd like to be able to get a correct DateTime for the NEXT occurrence of a time that I can specify with just an hour and minute. I'd also like to be able to do this by specifying the same thing for that hour and minute, but for the next occurrence of that on (say) a Wednesday.

Also, note that if the current minute has already "started" (which I guess means that we're in 00 milliseconds of that minute) then, again, we need to find the "next" occurrence of that time.

An example with (say) getting a DateTime for the next 10:34 AM and next 12:45 PM that's on a Wednesday, would be greatly appreciated.

How can I do this in Joda?

like image 423
LuxuryMode Avatar asked Jan 05 '12 20:01

LuxuryMode


1 Answers

Something like this, for "next 10:34 AM on a Wednesday:"

DateTime getNextTimeOnDay(int dayOfWeek, int hourOfDay, int minuteOfHour)
{
    DateTime now = new DateTime();
    DateTime then = now
        .withDayOfWeek(dayOfWeek)
        .withHourOfDay(hourOfDay)
        .withMinuteOfHour(minuteOfHour)
        .withSecondOfMinute(0)
        .withMillisOfSecond(0);

    return then.isBefore(now) ? then.plusWeeks(1) : then;
}

DateTime nextWednesdayAtTenThirtyFour
    = getNextTimeOnDay(DateTimeConstants.WEDNESDAY, 10, 34);

// as of now, this is 2012-01-06T10:34:00.000-05:00
like image 197
Matt Ball Avatar answered Sep 28 '22 03:09

Matt Ball