Sayak Banerjee
Sayak Banerjee

Reputation: 1964

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.

Upvotes: 0

Views: 189

Answers (2)

Steve
Steve

Reputation: 148

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();

Upvotes: 1

DoubleDouble
DoubleDouble

Reputation: 1493

Use GregorianCalendar which extends Calendar. try something like:

GregorianCalendar currentTime = new GregorianCalendar();
GregorianCalendar targetTime = new GregorianCalendar();

//Get Day and Time from config file
targetTime.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);

//Add a week if the targetTime is from last Sunday
if (targetTime.before(currentTime))
{
    targetTime.add(Calendar.DAY_OF_YEAR, 7);
}

System.out.println(currentTime.getTime().toString() + ", " + targetTime.getTime().toString());

Upvotes: 0

Related Questions