javadatecalendar

Get a Date instance for a day of week and time


I have a config file from where I am reading a day of week and a time of day in 24 hour format. A sample entry looks like this:

NextRun=Sunday|15:00:00

I will parse them out into day and time variables. However, I want to find the equivalent millisecond timestamp for the next Sunday 3:00pm.

So for example, if today is Sunday 4:00pm or Tuesday 1:00am it will be the next Sunday 3:00pm, but if it is Sunday 2:30pm now, the expected time will be 30 minutes from now.


Solution

  • Get a Calendar instance and set it with the parsed time and day. If it has passed, add a week.

    Calendar c = Calendar.getInstance();
    c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    c.set(Calendar.HOUR_OF_DAY, 15);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    if (c.getTimeInMillis() - Calendar.getInstance().getTimeInMillis() < 0)
        c.add(Calendar.DAY_OF_YEAR, 7);
    return c.getTimeInMillis();