WorkDayDiff

Developed In: SQL — Contributed by: Martin Minka

I created this function to calculate "working day" difference of two dates. If you have table with list of holidays you may uncomment part in this function to exclude days of holidays also.
Martin Minka
SQL
  1. CREATE DEFINER=`root`@`%` FUNCTION `WorkDayDiff`(b date, a date) RETURNS int(11)
  2. DETERMINISTIC
  3. COMMENT 'working day difference for 2 dates'
  4. BEGIN
  5. DECLARE freedays int;
  6. SET freedays = 0;
  7.  
  8. SET @x = DATEDIFF(b, a);
  9. IF @x<0 THEN
  10. SET @m = a;
  11. SET a = b;
  12. SET b = @m;
  13. SET @m = -1;
  14. ELSE
  15. SET @m = 1;
  16. END IF;
  17. SET @x = abs(@x) + 1;
  18. /* days in first week */
  19. SET @w1 = WEEKDAY(a)+1;
  20. SET @wx1 = 8-@w1;
  21. IF @w1>5 THEN
  22. SET @w1 = 0;
  23. ELSE
  24. SET @w1 = 6-@w1;
  25. END IF;
  26. /* days in last week */
  27. SET @wx2 = WEEKDAY(b)+1;
  28. SET @w2 = @wx2;
  29. IF @w2>5 THEN
  30. SET @w2 = 5;
  31. END IF;
  32. /* summary */
  33. SET @weeks = (@x-@wx1-@wx2)/7;
  34. SET @noweekends = (@weeks*5)+@w1+@w2;
  35. /* Uncomment this if you want exclude also holidays
  36. SELECT count(*) INTO freedays FROM holiday WHERE d_day BETWEEN a AND b AND WEEKDAY(d_day)<5;
  37. */
  38. SET @result = @noweekends-freedays;
  39. RETURN @result*@m;
  40. END$$
  41.  
  42. DELIMITER ;

Current Tags

You must be logged in to tag this tool

thanks Martin, if you dont help, maybe I will be crazy jejeje thanks.

Votes

  • Rated 5.00 out of 5
Rated 5.00 out of 5 with 2 votes cast.
You must be logged in to vote.

Watches

2 members are watching this tool
You must be logged in to track this tool.

Provide Feedback

Please note:
HTML will be purified, but we allow for a number of HTML tags so that you have the flexibility to decorate your comment text to some extent. The comments allow the following HTML tags:

strong, b, em, blockquote, a, code, pre

To put code into your comment, simply encapsulate your code with
[code language="XXX"][/code], where XXX is any common language, for instance "PHP", "SQL", "C", etc.



You must be logged in to comment