Let’s say I have a date object marked for February 13th, 2013 at 11pm. I am trying to get the next soonest date object at say, 3am. So in this case, it will be February 14th, 2013 3am.
I could do this simply by adding 1 day to the date field and setting the time to 3:00am, but what about the following case:
I have a date object marked for February 14th, 2013 at 1am. Here, I would not need to add a day, but rather simply set the time.
Is there an elegant way to do this? Below is what i’ve done so far, which I think will work, but I was just wondering if there is an api out there that makes this easier. Something like getNextSoonestDate() or something
Calendar calendar = Calendar.getInstance();
//myDate is some arbitrary date, like one of the examples posted above (i.e. feb 13th 11pm)
calendar.setTime(myDate);
//set the calender to be 3am
calendar.set(Calendar.HOUR_OF_DAY, 3);
//check if this comes before my current date, if so we know we need to add a day
if (calendar.getTime().before(myDate)){
calendar.add(Calendar.DAY_OF_YEAR, 1);
}
I don’t think there’s a pre-written method to do what you want to do, but writing a utility method is simple enough.
With that said, your code is close but will not work properly if
myDateis between3:00:00.001and3:59:59.999(I assume you’d want it to return the occurrence on the next day in this case) — you need to zero out the less significant fields: