7

I want two dates. 1) Current date in MM/dd/yy format 2) Modified date which will be the adition of five business days(Mon-Fri) to current date and it should be in MMM dd, yyyy format.

So if my current is 9th june than currentDate should be 06/09/14 and modifiedDate should be Jun 13, 2014.

How to do this?

Himanshu Tyagi
  • 5,201
  • 1
  • 23
  • 43
Anup Ganatra
  • 366
  • 1
  • 6
  • 23
  • for format part of question: http://stackoverflow.com/questions/11356109/improper-result-of-simpledateformat – jmj Jun 09 '14 at 05:31
  • 3
    You should understand that this site will help you when you need a help with your code. But they can not do researches on-behalf of you? So try something and ask help for any trouble with code. Try to use JODA framwork [link](http://www.joda.org/joda-time/) – Cyclops Jun 09 '14 at 05:31
  • @Meno reopened it, your link is probably more closer than what I marked initially, although business days can vary – jmj Jun 09 '14 at 06:25

3 Answers3

16

This will add working days (Mon-Fri) and will present dates in the required format.

UPDATED 6 Jul 2020

  1. Now custom days can be used as non working days (see the list NON_BUSINESS_DAYS)
  2. Now even the past date can be calculated as well (set businessDays as negative val)

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class BusinessDateExamples {

    private static final List<Integer> NON_BUSINESS_DAYS = Arrays.asList(
                Calendar.SATURDAY,
                Calendar.SUNDAY
            );
    
    /**
     * Returns past or future business date
     * @param date starting date
     * @param businessDays number of business days to add/subtract
     *          <br/>note: set this as negative value to get past date
     * @return past or future business date by the number of businessDays value
     */
    public static Date businessDaysFrom(Date date, int businessDays) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        for (int i = 0; i < Math.abs(businessDays);) {
            // here, all days are added/subtracted
            calendar.add(Calendar.DAY_OF_MONTH, businessDays > 0 ? 1 : -1);
            
            // but at the end it goes to the correct week day.
            // because i is only increased if it is a week day
            if (!NON_BUSINESS_DAYS.contains(calendar.get(Calendar.DAY_OF_WEEK))){
                i++;
            }
        }
        return calendar.getTime();
    }
    
    public static void main(String...strings) {
        SimpleDateFormat s = new SimpleDateFormat("MM/dd/yy ( MMM dd, yyyy )");
        
        Date date = new Date();
        int businessDays = 5;
        
        System.out.println(s.format(date));
        
        System.out.print("+ " + businessDays + " Business Days = ");
        System.out.println(s.format(businessDaysFrom(date, businessDays)));
        
        System.out.print("- " + businessDays + " Business Days = ");
        System.out.println(s.format(businessDaysFrom(date, -1 * businessDays)));
    }
}

    Date date=new Date();
    Calendar calendar = Calendar.getInstance();
    date=calendar.getTime(); 
    SimpleDateFormat s;
    s=new SimpleDateFormat("MM/dd/yy");
    
    System.out.println(s.format(date));
    
    int days = 5;
    for(int i=0;i<days;)
    {
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        //here even sat and sun are added
        //but at the end it goes to the correct week day.
        //because i is only increased if it is week day
        if(calendar.get(Calendar.DAY_OF_WEEK)<=5)
        {
            i++;
        }

    }
    date=calendar.getTime(); 
    s=new SimpleDateFormat("MMM dd, yyyy");
    System.out.println(s.format(date));

Ref : https://stackoverflow.com/a/15339851/3603806 and https://stackoverflow.com/a/11356123/3603806

Himanshu Tyagi
  • 5,201
  • 1
  • 23
  • 43
  • Some countries have working weeks Sunday-Thursday. As a naive solution this will work, but please be mindful of date-time-calendar edge cases. Reference: https://en.wikipedia.org/wiki/Workweek_and_weekend#Around_the_world – 50shadesofbae Jul 25 '18 at 16:34
  • This solution considers Friday and Saturday as the weekend. Calendar.DAY_OF_WEEK starts with Sunday (Sunday has value 1) – Kelo Aug 08 '19 at 22:28
  • The method `businessDaysFrom()` contains an error. The second row should be `calendar.setTime(date);` – Hassenboy Sep 04 '20 at 14:12
  • @Hassenboy You are right, I carried that from previous solution, missed to update it! Updated! Thanks – Himanshu Tyagi Sep 08 '20 at 18:04
  • Why do i think that i++ in for loop is not ok and in general while loop should have been used if you do i++ – kyrpav Aug 17 '21 at 13:09
9

The notion of working days is not implemented in Java, it's too subject to interpretation (for example, many international companies have their own holidays). Code below uses isWorkingDay(), which only returns false for weekends - add your holidays there.

public class Test {

    public static void main(String[] args) {
        Calendar cal = new GregorianCalendar();
        // cal now contains current date
        System.out.println(cal.getTime());

        // add the working days
        int workingDaysToAdd = 5;
        for (int i=0; i<workingDaysToAdd; i++)
            do {
                cal.add(Calendar.DAY_OF_MONTH, 1);
            } while ( ! isWorkingDay(cal));
        System.out.println(cal.getTime());
    }

    private static boolean isWorkingDay(Calendar cal) {
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY)
            return false;
        // tests for other holidays here
        // ...
        return true;
    }

}
Oliv
  • 10,221
  • 3
  • 55
  • 76
1

Here is the code sample to add dates. You may modify in order to you can only add business days.

    SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("MMM dd, yyyy");
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());

    System.out.println(sdf1.format(calendar.getTime()));
    calendar.add(Calendar.DATE,6);
    System.out.println(sdf2.format(calendar.getTime()));
Oliv
  • 10,221
  • 3
  • 55
  • 76
indika
  • 821
  • 7
  • 13