Question

PL/SQL - Calculate Number of Business Days in a Given Month

Asked by: davystocks

Hi,
I urgently need to calculate the number of business days in a given month. I realise that there are a number of submissions that calculate weekdays etc, but I specifically need to get the number of business days (in a 5 day working week) in a month, taking into account public holidays if possible.
Thanks.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-04-23 at 03:44:50ID22527495
Tags

calculate

,

days

,

business

,

month

Topics

Databases Miscellaneous

,

Oracle Database

Participating Experts
6
Points
500
Comments
11

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. holidays
    Hello experts. I have a short code that calculates business days for a field when a button is clicked. Is there a way to get it to evaluate holidays as well. dt=Cdat(Today()) Do While cntr<5 dt = dt+1 If Weekday(dt)>1 And Weekday(dt)<7 The...
  2. Weekday Calculation
    Crystal Reports 9: I got this formula that is supposed to calculate the weekdays in the month and it supposed to not include saturday and sunday. This is what I have. Local DateTimeVar d1 := PrintDate; d1 := DateSerial(Year(d1), Month(d1), 1); Local DateTimeVar d2 := Pr...
  3. Weekday function
    I'm looking for an efficient function that returns a date that is x weekdays after a given date (y).
  4. calculate next working day excluding holidays
    hi experts. i need to calculate the next working / business day excluding list of holiday dates. I have found a couple of forumalas but unsure how to tie them together. I would like the cell to display the day date formast in one cell ie" Monday 12th January 2009" ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: jwahlPosted on 2007-04-23 at 03:53:36ID: 18957314

do you have a table for the public holidays? they may vary ...

 

by: davystocksPosted on 2007-04-23 at 03:57:43ID: 18957338

Thanks for your quick reply. I currently don't have access to a public holidays table, but the 500 points will go for calculating the business days in a given month.

 

by: gbshahaqPosted on 2007-04-23 at 04:11:30ID: 18957414

take a look at the scripts posted in this thread -this should help you achieve exactly what you want - including adding in holidays....

Calculating Business Days
http://www.thescripts.com/forum/thread181183.html

 

by: jwahlPosted on 2007-04-23 at 04:16:34ID: 18957433

if you need a function for this: this one counts the working days (mo- fr) for a given date. the calculating is based on

SELECT TO_CHAR(SYSDATE, 'D') FROM dual;

if this returns 2 for monday (6 for friday), it will work (depending on your NLS settings this may vary), otherwise you have to change the code.

 CREATE OR REPLACE FUNCTION get_working_days (
     p_start_date IN DATE
     )
 RETURN NUMBER IS
     v_last_day NUMBER;
     v_cnt NUMBER := 0;
 BEGIN
     SELECT TO_CHAR(LAST_DAY(p_start_date), 'DD')
     INTO   v_last_day
     FROM   dual;
     --
     FOR i IN 1..v_last_day
     LOOP
         IF TO_CHAR(p_start_date - 1 + i, 'D') BETWEEN 2 AND 6 THEN
            v_cnt := v_cnt + 1;
         END IF;
     END LOOP;
     --
     RETURN(v_cnt);
     --
 END;

 

 

by: NickUpsonPosted on 2007-04-23 at 07:53:42ID: 18958839

you need a data source, for each country, for actual working days. Different countries have designated days off, e.g. US has thanksgiving, the UK has various mondays called bank holidays.

 

by: awking00Posted on 2007-04-23 at 08:44:57ID: 18959222

What is the source for your "given" month (this will obviously need to include the year as well)? If it is a date field, then jwahl's function will get you what you need although I think it may need a modification to make sure that the date parameter passed in is adjusted to the first day of the month. This can be done changing this
IF TO_CHAR(p_start_date - 1 + i, 'D') ...
to this -
IF TO_CHAR(trunc(p_start_date,'month') - 1 + i, 'D') ...
If the source is something other than a date field, we can create a function to deal with that as well. For example, if it is character data in the form of 'yyyymm', the following function will work:
create or replace function get_bus_days(yr_mth_in in varchar2) return number is
beg_day   date;
end_day   date;
tot_days  pls_integer;
bus_days  pls_integer := 0;
day_of_wk pls_integer;

begin
beg_day := to_date(yr_mth_in,'yyyymm');
end_day := add_months(beg_day,1) - 1;
tot_days := end_day - beg_day;
for i in 0..tot_days
loop
day_of_wk := to_number(to_char(beg_day + i,'D'));
if day_of_wk between 2 and 6 then
bus_days := bus_days + 1;
end if;
end loop;
return bus_days;
end;
/

 

by: gatorvipPosted on 2007-04-23 at 09:15:25ID: 18959464

Here's an adaptation from jwahl's code. It can be easily adapted to a function.

Some holidays are taken into consideration - there are two kinds: fixed date (Independence Day) or variable date (Thanksgiving). You can add your own.

declare      
   startDate date := sysdate;
   ctrDate date ;  
   numMonth number;
   numDay number;
   dayCount number := 0;
 BEGIN
     dbms_output.enable;          
     ctrDate := trunc(startDate, 'MM');          
     
     -- calculate business days in the month
     while (ctrDate <= last_day(startDate))
     loop
         if to_char(ctrDate, 'D') between 2 and 6 then
            dayCount := dayCount + 1;
         end if;
         ctrDate := ctrDate+1;              
     end loop;
     
     numMonth := to_number(to_char(startDate, 'MM'));
     numDay := to_number(to_char(startDate, 'DD'));
     
     -- eliminate 1/1, 7/4, 12/25
     if ((numMonth = 1) and to_number(to_char(to_date('01/01', 'MM/DD'), 'MM')) between 2 and 6 ) or
        ((numMonth = 7) and to_number(to_char(to_date('07/04', 'MM/DD'), 'MM')) between 2 and 6 ) or
        ((numMonth = 12) and to_number(to_char(to_date('12/25', 'MM/DD'), 'MM')) between 2 and 6 )
       then dayCount := dayCount-1;
     end if;
     
     
     -- eliminate variable date public holidays that fall on working days
     -- MLK = 3rd Monday in January
     -- Memorial = last Monday in May
     -- Labor = first Monday in September
     -- Thanksgiving = 4th Thursday in November    
     if numMonth in (1,5,9,11) then
       dayCount := dayCount-1;
     end if;
     
     dbms_output.put_line('#working days in this month: '||dayCount);
 END;

 

by: awking00Posted on 2007-04-23 at 10:22:32ID: 18959983

Just to "muddy the waters" even more on the holiday issue, if January 1 falls on a Saturday, you would need to add an extra "non-business" day to the prior December calculation since the New Year's holiday would be observed on December 31. Also, if Veteran's day is observed, then if numMonth = 11 then dayCount := dayCount - 2;
Good luck!

 

by: SJT2003APosted on 2007-04-23 at 11:11:02ID: 18960338

If I were in your shoes and asked the same to write for such thing, I would the following

Simple example brain-feed for your goal.

Store all the holiday dates in a table (except saturday and sunday general public holidays) with only federal and other state/provincial/corporate holidays) and calculate the days for the given parameter.

Write a simple function which accepts a month (numeric) parameter and returns the number of days.
Taking the given inputted parameter, I would check the date existence in the holiday list table for the same month and subtract that number of holiday dates existence from the given month and return the result

For example

SELECT myNumDays(4) FROM dual;

FUNCTION myNumDays(month IN integer)
would find out if any dates exist in the holiday list table that are of 4th month and return the count.
That count is subtracted from the number of days of given month, for example April, 30 - 8 (4 * sat/sun) = 24 - number of holiday count for that april month.

The function should be able to find out if a holiday falls on SATURDAY or SUNDAY would exclude from the calculation as SAT and SUNDAYs are already assumed holidays.

Check it out. Good luck :)



 

by: SJT2003APosted on 2007-04-23 at 11:12:13ID: 18960345

On top of my note above, I totally agree with others that holidays vary from country to country hence there is no ready-made function that works for all.

Good luck :)

 

by: davystocksPosted on 2007-05-02 at 02:53:54ID: 19014477

Thanks for your help guys. There was some room for thought in most of the responses. Hope it is ok to share out some of the points, but the majority went to jwahl as it was the basis for solving my problem.  ; ^)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...