2016-04-06 2 views
1

Я сейчас работаю над HR system, и у него есть опция для get 10 consecutive days (working days except weekends) отпуска в своем модуле управления отпуска. Это приложение J2EE.Получить 'N' количество последовательных будних дней с указанной даты

Все, что я хочу, чтобы get 'N' number of consecutive weekdays from the given date

ли кто-нибудь знает, как достичь этой проблемы?

P.S: Я не использую какие-либо 3-библиотеки, как JodaTime ..

Вот код моего контроллера для применения отпуска один дня. Это не имеет ничего общего с последовательностью дней. но отправляю это здесь, чтобы доказать, что я делаю что-то серьезное ..

if (action.equals("applyLeave")) { 

    Leave l = new Leave(); 

    int userid = Integer.parseInt(request.getParameter("userid")); 
    int leavetype = Integer.parseInt(request.getParameter("leavetype")); 
    String from = request.getParameter("from"); // from time 
    String to = request.getParameter("to"); // to time 
    double total = Double.parseDouble(request.getParameter("total")); // total hours 

    String r1 = request.getParameter("rep1"); 
    String r2 = request.getParameter("rep2"); 

    if (r1 == null || r1.isEmpty()) { 
     r1 = "0"; 
    } 

    if (r2 == null || r2.isEmpty()) { 
     r2 = "0"; 
    } 

    int rep1 = Integer.parseInt(r1); 
    int rep2 = Integer.parseInt(r2); 

    String reason = request.getParameter("reason"); 
    String date = request.getParameter("date"); 

    l.setUser(userid); 
    l.setLeavetype(leavetype); 
    l.setDate(date); 
    l.setFrom(from); 
    l.setReason(reason); 
    l.setRep1(rep1); 
    l.setRep2(rep2); 
    l.setTo(to); 
    l.setTotal(total); 

    dao.saveLeave(l); 

    // get manager of the department 
    UserDao udao = (UserDao) ctx.getBean("udao"); 
    DepartmentDao ddao = (DepartmentDao) ctx.getBean("depdao"); 
    NotificationDao notificationDao = (NotificationDao) ctx.getBean("notificationDao"); 
    User u = udao.getUserByUserID(userid).get(0); 
    int department = u.getDepartment(); 
    Department d = ddao.getDepartmentByID(department).get(0); 
    int manager = d.getManager(); 

    // save a notification for the respective manager 
    // insert notification 
    String text = u.getFirstname() + " " + u.getLastname() + " has applied for a leave"; 
    Notification n = new Notification(); 
    n.setUserid(manager); 
    n.setFk(dao.getLeaveID()); 
    n.setType(3); 
    n.setText(text); 
    notificationDao.saveNotification(n); 

    PrintWriter out = res.getWriter(); 
    res.setContentType("text/html"); 
    Gson gson = new Gson(); 
    JsonObject myObj = new JsonObject(); 
    myObj.add("message", gson.toJsonTree("Successfully Inserted")); 
    out.println(myObj.toString()); 
    out.close(); 

} 
+0

@Psioniax, я закончил большую часть вещей в приложении, но я борюсь, чтобы получить эти дни подряд. Я искал google для решения, но я не смог найти. –

+0

Редактировать свой вопрос, чтобы включить код –

+0

@Psioniax, отредактированный с кодом –

ответ

1
List<Date> holidays = conf.getHolidays(); 
List<Date> nWorkingDays = new ArrayList<>(); 

// get the current date without the hours, minutes, seconds and millis 
Calendar cal = Calendar.getInstance(); 
cal.set(Calendar.HOUR_OF_DAY, 0); 
cal.set(Calendar.MINUTE, 0); 
cal.set(Calendar.SECOND, 0); 
cal.set(Calendar.MILLISECOND, 0); 

// iterate over the dates from now and check if each day is a business day 
int businessDayCounter = 0 
while (businessDayCounter < n) { //You want n working days 
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); 
    if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY && !holidays.contains(cal.getTime())) { 
     businessDayCounter++; 
     nWorkingDays.add(cal.getTime()); 
    } 
    cal.add(Calendar.DAY_OF_YEAR, 1); 
} 

return nWorkingDays; 

адаптирован из этого ответа: https://stackoverflow.com/a/15626124/1364747

+0

Это сработало. Спасибо ! –

1

Не уверен, требуется ли вам решение в стандартной Java (помеченным JavaScript именно), но я предполагаю, что вы могли бы сделать это следующим образом:

int numberOfDays = 10; 

// Get current date 
Calendar calendar = Calendar.getInstance(); 

//Repeat until all consecutive weekdays consumed 
while(numberOfDays >0) { 
    int day = calendar.get(Calendar.DAY_OF_WEEK); 

    if((day != Calendar.SUNDAY) && (DAY != Calendar.SATURDAY)) { 
     numberOfDays--; 
    } 

    calendar.add(Calendar.DAY,1); 
} 

// Calendar now contains the date after consuming all 
// consecutive week days 
return calendar; 

ВНИМАНИЕ: Не скомпилировали и не выполнили этот пример, поэтому могут возникнуть исключения.

Смежные вопросы