2

I'm developing an app in Android which have a service that must be executed every Thursday and Sunday at 22:00

What I do need, is to set a Calendar to that day and time. However, I'm not sure about how to do it.

Calendar calendar = Calendar.getInstance();

This is giving me a calendar with the current date and time.

I know I can add days, minutes, hours, etc. But, is there any way to directly setNext("thursday")?

I don't want to do many maths there. I mean I'm looking for an answer which doesn't need to calculate how many minutes/hours/days are left till next thursday.

Thank you!!

Reinherd
  • 5,476
  • 7
  • 51
  • 88

4 Answers4

3

I've found the below solution simpler, a bit more portable as it doesn't involve much math. Once you set it to Thursday I believe you can use thesetTime() method on the calendar object to set it to 22:00.

//dayOfWeekToSet is a constant from the Calendar class
//c is the calendar instance
public static void SetToNextDayOfWeek(int dayOfWeekToSet, Calendar c){
    int currentDayOfWeek = c.get(Calendar.DAY_OF_WEEK);
            //add 1 day to the current day until we get to the day we want
    while(currentDayOfWeek != dayOfWeekToSet){
        c.add(Calendar.DAY_OF_WEEK, 1);
        currentDayOfWeek = c.get(Calendar.DAY_OF_WEEK);
    }
}

  //usage:
  Calendar c = Calendar.getInstance();
  System.out.println(c.getTime());
  SetToNextDayOfWeek(Calendar.THURSDAY,c);
    System.out.println(c.getTime());
JMoy
  • 491
  • 4
  • 6
1

Not many maths, solved this, so clean:

    int weekday = calendar.get(Calendar.DAY_OF_WEEK);  
    if (weekday!=Calendar.THURSDAY){//if we're not in thursday
        //we calculate how many days till thursday
        //days = The limit of the week (its saturday) minus the actual day of the week, plus how many days till desired day (5: sunday, mon, tue, wed, thur). Modulus of it.
        int days = (Calendar.SATURDAY - weekday + 5) % 7; 
        calendar.add(Calendar.DAY_OF_YEAR, days);
    }
    //now we just set hour to 22.00 and done.

Credit to: http://www.coderanch.com/t/385117/java/java/date-Monday

I just adapted and explained the code.

Reinherd
  • 5,476
  • 7
  • 51
  • 88
0

Try this?

c.add(c.DAY_OF_YEAR, -7);

or

c.add(c.DAY_OF_YEAR, +7);
António Almeida
  • 9,620
  • 8
  • 59
  • 66
Amod Gokhale
  • 2,346
  • 4
  • 17
  • 32
  • 1
    This is adding 7 days to the actual day. Not what I want, as if I run this on a Monaday, it will be executed again next monday. – Reinherd Sep 27 '13 at 13:36
-1

calendar.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);

Robert Goodrick
  • 190
  • 1
  • 11