0

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.

Sayak Banerjee
  • 1,954
  • 3
  • 25
  • 58
  • 2
    I think you will want to look at JodaTime and its time difference API, for [example](http://stackoverflow.com/questions/18119665/geting-duration-of-2-times/18120233#18120233), [example](http://stackoverflow.com/questions/18974729/how-to-get-the-time-since-midnight-in-seconds/18975189#18975189) and [example](http://stackoverflow.com/questions/12851934/how-to-find-difference-between-two-joda-datetime-in-minutes/12852021#12852021) – MadProgrammer Nov 26 '13 at 20:48
  • This is on a client's network, so I cannot unfortunately use an API for this. – Sayak Banerjee Nov 26 '13 at 20:52
  • @Sayak Joda-Time is a local library, a .jar file, installed as part of your app. Not a web service etc. so no network involved. – Basil Bourque Nov 26 '13 at 22:01
  • I see that, but I cannot use a third part library either. Thanks for the help, I got this resolved now :) – Sayak Banerjee Nov 26 '13 at 22:13

2 Answers2

1

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();
Steve
  • 148
  • 1
  • 8
0

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());
DoubleDouble
  • 1,493
  • 10
  • 25