Daniel Vágner Daniel Vágner - 3 years ago 168
Android Question

Add days, android studio

in my application user can chose date with calendar and then chose how many days he wants add. But there is my problem. Adding days working excelent, but i need to skip weekdays. For example you will choose day and add +15days, result will be Saturday or Sunday. But in this case i need to get always mondey if result is one of these days.

Here is method for adding days

public static Date addDays(Date date, int days) {

Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days + FirstClass.hotovo);
return cal.getTime();

}


Thank you for your help, i am not expert in programming. I am amateur and i am still learning..

JRG JRG
Answer Source

You should check what is the resultant day i.e. check if its SATURDAY or SUNDAY and then adding 2 or 1 to get next MONDAY.

NOTE: I do not know what is FirstClass.hotovo so I have removed temporary from below code and you can add it as you would have it in your project. Below is to demonstrate how to check day and add 1 or 2 day respectively.

Here is the sample code.

Caller:

addDays(new Date(), 18);

Your method:

public static Date addDays(Date date, int days) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.DATE, days);
    Log.d("TEST", "BEFORE CHECKING: " + cal.getTime().toString());
    // SATURDAY is the last day of week so add 2 days
    if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
        cal.add(Calendar.DATE, 2);
        // SUNDAY is the first day of week so add 1 day
    } else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
        cal.add(Calendar.DATE, 1);
    } // else not required as it means its one of the week day
    Log.d("TEST", "AFTER UPDATING: " + cal.getTime().toString());
    return cal.getTime();
}

Sample Run

Resultant day was SATURDAY so adding 2 days to get MONDAY

07-25 15:46:55.729 4219-4219/? D/TEST: BEFORE CHECKING: Sat Aug 12 15:46:55 PDT 2017
07-25 15:46:55.729 4219-4219/? D/TEST: AFTER UPDATING: Mon Aug 14 15:46:55 PDT 2017

Resultant day was SUNDAY so adding 1 day to get MONDAY

07-25 15:47:57.634 4322-4322/? D/TEST: BEFORE CHECKING: Sun Aug 13 15:47:57 PDT 2017
07-25 15:47:57.634 4322-4322/? D/TEST: AFTER UPDATING: Mon Aug 14 15:47:57 PDT 2017

Resultant day was TUESDAY so not adding any more days

07-25 15:52:27.115 4445-4445/? D/TEST: BEFORE CHECKING: Tue Aug 15 15:52:27 PDT 2017
07-25 15:52:27.115 4445-4445/? D/TEST: AFTER UPDATING: Tue Aug 15 15:52:27 PDT 2017
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download