Count days between two dates, excluding weekends (MySQL only)

后端 未结 5 649
离开以前
离开以前 2020-11-28 16:26

I need to calculate the difference (in days) between two dates in MySQL excluding weekends (Saturday and Sunday). That is, the difference in days minus the number of Saturda

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 16:49

    Illustration:

    mtwtfSSmtwtfSS
      123456712345   one week plus 5 days, you can remove whole weeks safely
      12345-------   you can analyze partial week's days at start date
      -------12345   or at ( end date - partial days )
    

    Pseudocode:

    @S          = start date
    @E          = end date, not inclusive
    @full_weeks = floor( ( @E-@S ) / 7)
    @days       = (@E-@S) - @full_weeks*7   OR (@E-@S) % 7
    
    SELECT
      @full_weeks*5 -- not saturday+sunday
     +IF( @days >= 1 AND weekday( S+0 )<=4, 1, 0 )
     +IF( @days >= 2 AND weekday( S+1 )<=4, 1, 0 )
     +IF( @days >= 3 AND weekday( S+2 )<=4, 1, 0 )
     +IF( @days >= 4 AND weekday( S+3 )<=4, 1, 0 )
     +IF( @days >= 5 AND weekday( S+4 )<=4, 1, 0 )
     +IF( @days >= 6 AND weekday( S+5 )<=4, 1, 0 )
     -- days always less than 7 days
    

提交回复
热议问题