Search code examples
javaandroiddatetimejodatime

How to get a DateTime/Calendar instance with the Time of next Monday 6:00am?


How can I get the millisecond value (since Unix Epoch) of a specific time next week. When my code executes, it needs to get next Monday at 6:00 am in milliseconds. I cannot pass in any static values, it has to be dynamic.

For example:

If it's currently Tue 05/05/2020 21:30 the code must return the millisecond value of Mon 11/05/2020 06:00

Or

If it's currently Mon 04/05/2020 05:59 the code must return the millisecond value of Mon 04/05/2020 06:00

I've read alot of the similar questions but none of them give a definitive answer or only focus on the day of the week and do not factor the specific time (in my case 06:00). I've looked into using TemporalAdjusters but I'm hesitant to include them in my android project as they require API 26 (my min is 21). I've looked at JodaTime but couldn't find a suitable function to round to a specific time.

In the code below, I attempted to implement some sort of solution but came across issues when the DateTime was on a Monday but after 06:00.

Calendar date1 = Calendar.getInstance();
date1.setTimeInMillis(System.currentTimeMillis());

while (date1.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
    date1.add(Calendar.DATE, 1);
}
while (date1.get(Calendar.HOUR_OF_DAY) < 6){
    date1.add(Calendar.HOUR,1);
}

Solution

  • Joda time is great for stuff like this. For example, the millisecond of the current day is DateTime.now().withTimeAtStartOfDay(). Which day of the week is DateTime.now().dayOfWeek() (Monday = 1, Tuesday = 2, etc.). There is a plusDays() method to move to the future. Combine these with a switch statement to figure out the number of days to add and you should arrive at the desired solution. Oh, and re-reading your question, it should be straightforward to add the number of milliseconds necessary to get to 6:00 from the start of the day...sorry I missed that ;-) Good luck!