如何获取当前日期并在Java中添加五个工作日

Anu*_*tra 5 java datetime date

我想要两个约会.1)MM/dd/yy格式的当前日期2)修改日期,即5个工作日(周一至周五)至当前日期的加法,应为MMM dd,yyyy格式.

因此,如果我的当前时间是6月9日,那么currentDate应该是06/09/14,并且modifiedDate应该是2014年6月13日.

这该怎么做?

Him*_*agi 12

这将增加工作日(周一至周五),并以所需格式显示日期.

    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));
Run Code Online (Sandbox Code Playgroud)

参考:https://stackoverflow.com/a/15339851/3603806/sf/answers/794928641/


Oli*_*liv 9

工作日的概念没有在Java中实现,它太受制于解释(例如,许多国际公司都有自己的假期).下面的代码使用isWorkingDay(),只在周末返回false - 在那里添加你的假期.

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;
    }

}
Run Code Online (Sandbox Code Playgroud)