Count days between two dates with Java 8 while ignoring certain days of week

后端 未结 2 562
臣服心动
臣服心动 2020-12-15 11:54

Below I have 3 methods. The first is very simple. It just counts the total number of days. The second, however, will not only count the days, but will ignore the days of the

2条回答
  •  [愿得一人]
    2020-12-15 12:34

    You you are using wrong Excel formula. See the section "Using SUM and INT function to count the number of workdays" of the site that you have provided. It is stating the formula as:

    =SUM(INT((WEEKDAY(A2-{2,3,4,5,6})+B2-A2)/7))
    

    In Excel, Sunday is 1 and Saturday is 7. The numbers inside the curly braces indicates the day-of-weeks to be included. So for your case the formula will be:

    =SUM(INT((WEEKDAY(A2-{2,3,5,7})+B2-A2)/7))
    

    Please see the attached screenshot:

    enter image description here

    It is returning 2247 as the following code returns:

    import java.time.DayOfWeek;
    import java.time.LocalDate;
    import java.time.Month;
    import java.time.Year;
    import java.time.format.DateTimeFormatter;
    import java.time.temporal.ChronoUnit;
    
    
    public class SO25798876 {
    
        public static void main(String[] args) {
            String strStartDate = "09/07/2014";
            String strEndDate = "06/13/2025";
            String pattern = "MM/dd/yyyy";
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            LocalDate startDate = LocalDate.parse(strStartDate, formatter);
            LocalDate endDate = LocalDate.parse(strEndDate, formatter);
    
            int count = 0;
    
            while(startDate.isBefore(endDate) || startDate.isEqual(endDate)) {  // you may want to not to use the isEqual method        
                DayOfWeek dayOfWeek = startDate.getDayOfWeek();         
    
                if(!(dayOfWeek == DayOfWeek.SUNDAY || dayOfWeek == DayOfWeek.WEDNESDAY || dayOfWeek == DayOfWeek.FRIDAY)) {
                    count++;
                }           
    
                startDate = startDate.plusDays(1);
            }
    
            System.out.println(count);  
        }
    }
    

    You also have mentioned your doubt that the java.time may be not considering leap year, which is wrong, if you add the following piece of code

    long year = startDate.getYear();
    
    if(Year.isLeap(year)) {
        Month month = startDate.getMonth();
    
        if(month == Month.FEBRUARY && startDate.getDayOfMonth() == 29) {
            System.out.println("Calculated 29th Feb for the year: " + year);
        }
    }
    

    You will see that it is printing:

    Calculated 29th Feb for the year: 2016
    Calculated 29th Feb for the year: 2020
    Calculated 29th Feb for the year: 2024
    

    Lastly the count will be 2247 which matches the Excel result.

    Happy coding.

    -Tapas

提交回复
热议问题