计算两个日期之间的天数,不包括周末(仅限MySQL)
作者:互联网
我需要计算MySQL中两个日期之间的差异(以天为单位),不包括周末(周六和周日).也就是说,天数之差减去周六和周日之间的数量.
目前,我只计算使用日期:
SELECT DATEDIFF('2012-03-18', '2012-03-01')
这个返回17,但我想排除周末,所以我想要12(因为第3和第4,第10和第11和第17是周末的日子).
我不知道从哪里开始.我知道WEEKDAY()函数和所有相关函数,但我不知道如何在这种情况下使用它们.
解决方法:
插图:
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 )
伪代码:
@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
标签:mysql,date,datediff,weekend 来源: https://codeday.me/bug/20190714/1455809.html