24
Tue, Dec
1 New Articles

The CL Corner: Handling Those Pesky Holidays

CL
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Holidays should be fun! With CL-based variables, at least they're not a headache.

 

In the last column in this series, we looked at how to calculate a date such that it would be a minimum of 60 days from an arbitrary date and ensure that the calculated date did not fall on a Saturday or Sunday. We accomplished this using the i5/OS APIs CEEDAYS, CEEDYWK, and CEEDATE. We noticed, however, that holidays were not being handled. When avoiding a Saturday or Sunday calculation, we would use the following Monday, which might be a holiday. In today's column, we'll look at one possible solution for bypassing holidays. Note that there are many, many possible ways to handle holidays. This is simply one: one that may be better or worse than other methods, depending on your situation.

 

As we learned in "So You're Looking for a Date?", Lilian dates are represented by a sequential number where October 15, 1582, is 1; October 16, 1582, is 2; and March 21, 2008, is 155387. This attribute seems ready-made for an array of work vs. non-work days with the Lilian date being an offset into the array, and this is just what we will do. As it is unlikely that we need to support dates far in the past (back to 1582) or far into the future (the year 9999), we will arbitrarily create an array of 1-byte character fields representing the dates January 1, 1940, through December 31, 2199, where a value of 0 indicates a work day and a value of 1 a non-work day. As January 1, 1940, corresponds to Lilian date 130470 and December 31, 2199, corresponds to Lilian date 225433, this means we will create an array of 94964 1-byte elements (225433 - 130470 + 1). And we will not allow the small implementation detail that CL doesn't support arrays, or a variable length greater than 32767 bytes, to deter us!

 

The following program, CRTCAL, creates a user space (*USRSPC) named CALENDAR in library QUSRSYS. The *USRSPC, when created, is initialized so that every day is a work day. Following that, CRTCAL marks each Saturday and Sunday in the *USRSPC as a non-work day.

 

Pgm                                                     

Dcl        Var(&UsrSpc_Ptr) Type(*Ptr)                  

Dcl        Var(&WeekEnd)    Type(*Char) Stg(*Based) +   

                              Len(2) BasPtr(&UsrSpc_Ptr)

                                                        

Dcl        Var(&Size)       Type(*Int) Value(94964)     

                                                        

Call       Pgm(QUSCRTUS) Parm('CALENDAR  QUSRSYS' ' ' + 

               &Size '0' '*USE' 'Calendar array')       

Call       Pgm(QUSPTRUS) Parm('CALENDAR  QUSRSYS' +     

             &UsrSpc_Ptr)                               

                                                         

ChgVar     Var(%Ofs(&UsrSpc_Ptr)) +                     

             Value(%Ofs(&UsrSpc_Ptr) + 5)               

DoUntil    Cond(%Ofs(&UsrSpc_Ptr) > 94964)              

           ChgVar Var(&WeekEnd) Value('11')             

           ChgVar Var(%Ofs(&UsrSpc_Ptr)) +       

                  Value(%Ofs(&UsrSpc_Ptr) + 7)   

EndDo                                            

EndPgm

 

Without going into the details of the Create User Space (QUSCRTUS) API (they can be found here), CRTCAL is creating the *USRSPC QUSRSYS/CALENDAR that is a minimum of 94964 bytes in size. Each byte is initialized to 0 and the user space has PUBLIC(*USE) authority. There are several additional parameters not shown. A key one is a parameter to replace the *USRSPC if it currently exists. The default is to not replace an existing *USRSPC, and I'm taking that default just in case you already have a *USRSPC by that name on your system. If you need to run CRTCAL several times when testing, you can either add the Replace parameter to the call to QUSCRTUS or use the DLTUSRSPC command prior to running CRTCAL.

 

After creating CALENDAR CRTCAL, we set the weekends as non-work days. To do this, we will use pointers and based variables. This is the real reason I chose an array based solution: I wanted to familiarize you with this capability/technique of CL, one that I believe is underutilized. First, CRTCAL gets a pointer to CALENDAR using the Retrieve Pointer to User Space (QUSPTRUS) API. This pointer, &UsrSpc_Ptr, will point to, or address, the first byte of the *USRSPC. As the first byte represents January 1, 1940, and we know from the CEEDYWK API (not shown) that this date is a Monday, CRTCAL adds 5 to the value of &UsrSpc_Ptr so that it now addresses January 6, 1940: a Saturday. CRTCAL then moves the 2-byte value 11 to variable &WeekEnd. This sets both the Saturday and Sunday bytes as being non-working (note that the variable &WeekEnd is defined as being *Based on &UsrSpc_Ptr so &WeekEnd is associated with whatever two bytes &UsrSpc_Ptr is currently addressing, in this case, Saturday, January 6, 1940, and Sunday, January 7, 1940), adds 7 to &UsrSpc_Ptr to address the next Saturday in CALENDAR, and then loops until all weekends in our supported range of dates are updated.

 

I will point out that there is one "bug" or exposure in CRTCAL, but I left it in to simplify the code. Namely, if December 31, 2199, was a Saturday, then updating Sunday, January 1, 2200 (which CRTCAL would do with the ChgVar &Weekend command as it's currently coded) could cause a MCH0601 error: "Space offset is outside of current limit." In the case of CRTCAL, this won't happen for two reasons. First, December 31, 2199, is not a Saturday. Second, *USRSPCs are created with sizes that are multiples of 4096. So even though CRTCAL asked for only 94964 bytes, additional bytes were allocated, so a byte is actually there for January 1, 2200. Building in a check for this situation, while easily done, would add code without any educational benefit, so I left it out.

 

Having created CALENDAR, now let's look at updating holidays. The following program, SETDAY, actually allows you to mark any given day as either a work day or a non-work day.

 

 

Pgm        Parm(&YYMDDay &Status)                       

Dcl        Var(&YYMDDay)    Type(*Char) Len(8)          

Dcl        Var(&Status)     Type(*Char) Len(5)          

Dcl        Var(&LilDay)     Type(*Int)                  

                                                        

Dcl        Var(&UsrSpc_Ptr) Type(*Ptr)                  

Dcl        Var(&Day)        Type(*Char) Stg(*Based) +   

                              Len(1) BasPtr(&UsrSpc_Ptr)

                                                         

Dcl        Var(&Base)       Type(*Int)  Value(130470)   

Dcl        Var(&Top)        Type(*Int)  Value(225433)   

                                                        

CallPrc    Prc(CEEDAYS) Parm((&YYMDDay) ('YYYYMMDD') +  

             (&LilDay) (*Omit))                         

                                                        

If         Cond((&LilDay *GE &Base) *And +              

                (&LilDay *LE &Top)) Then(Do)            

           Call Pgm(QUSPTRUS) Parm('CALENDAR  QUSRSYS' +

                  &UsrSpc_Ptr)                          

           ChgVar Var(%Ofs(&UsrSpc_Ptr)) +              

               Value(%Ofs(&UsrSpc_Ptr) + &LilDay - &Base)

           Select                                        

             When Cond(&Status = '*WORK') +             

                  Then(ChgVar Var(&Day) Value('0'))     

             When Cond(&Status = '*OFF') +              

                  Then(ChgVar Var(&Day) Value('1'))     

             OtherWise Cmd(SndPgmMsg +                  

                  Msg('Invalid status for day. +       

                  Valid values are *WORK and *OFF') +   

                  ToPgmQ(*Ext))                         

           EndSelect                                     

           EndDo                                        

Else       Cmd(SndPgmMsg +                              

                 Msg('Invalid date specified. +         

                 The valid range is Jan 1 1940 to Dec 31 +

                 2199.') ToPgmQ(*Ext))                   

EndPgm

 

SETDAY requires two parameters. The first, &YYMDDay, is the day we want to set and is formatted as YYMD. The second, &Status, is the status we want to assign to the day. The two supported values for &Status are *WORK and *OFF. Even with parameter validation (range checking and a valid value for &Status), the program is quite straightforward. SETDAY gets the Lilian date for the day passed in, retrieves &UsrSpc_Ptr (which addresses the first byte of the CALENDAR *USRSPC), calculates the byte offset into CALENDAR for the specified date by adding the Lilian date to &UsrSpc_Ptr and then subtracting the &Base (or starting) Lilian date value for January 1, 1940, and then sets the corresponding byte to the appropriate value. That's it!

 

Our last program, GREGTOLIL3, is shown below.

 

 

Pgm        Parm(&YYMDGreg)                               

Dcl        Var(&YYMDGreg)   Type(*Char) Len(8)           

Dcl        Var(&CurLilDate) Type(*Int)                    

Dcl        Var(&NewLilDate) Type(*Int)                   

Dcl        Var(&NewGregDt)  Type(*Char) Len(32)          

                                                         

Dcl        Var(&UsrSpc_Ptr) Type(*Ptr)                   

Dcl        Var(&Day)        Type(*Char) Stg(*Based) +    

                              Len(1) BasPtr(&UsrSpc_Ptr) 

                                                         

Dcl        Var(&Base)       Type(*Int)  Value(130470)    

Dcl        Var(&Top)        Type(*Int)  Value(225433)    

Dcl        Var(&DayOff)     Type(*Char) Len(1) Value('1')

                                                         

CallPrc    Prc(CEEDAYS) Parm((&YYMDGreg) ('YYYYMMDD') +  

             (&CurLilDate) (*Omit))                       

                                                         

If         Cond((&CurLilDate *GE (&Base - 60)) *And +    

                (&CurLilDAte *LE (&Top - 60))) Then(Do)  

           ChgVar Var(&NewLilDate) Value(&CurLildate + 60)

           Call Pgm(QUSPTRUS) Parm('CALENDAR  QUSRSYS' + 

             &UsrSpc_Ptr)                                

                                                         

           ChgVar Var(%Ofs(&UsrSpc_Ptr)) +               

             Value(%Ofs(&UsrSpc_Ptr) + &NewLilDate - +   

             &Base)                                      

           DoWhile Cond(&Day = &DayOff)                  

             ChgVar Var(%Ofs(&UsrSpc_Ptr)) +             

                      Value(%Ofs(&UsrSpc_Ptr) + 1)       

           EndDo                                         

           ChgVar Var(&NewLilDate) +                     

                    Value(%ofs(&UsrSpc_Ptr) + &Base)     

           CallPrc Prc(CEEDATE) Parm((&NewLilDate) +     

                   ('MM/DD/YYYY') (&NewGregDt) (*Omit)) 

                                                        

           SndPgmMsg Msg(&NewGregDt) ToPgmQ(*Ext)       

           EndDo                                        

Else       Cmd(SndPgmMsg +                               

               Msg('Date is outside the valid range.')) 

EndPgm                                                  

 

GREGTOLIL3 has one required parameter, &YYMDGreg, which is the starting date in YYMD format. After appropriate range checking, GREGTOLIL3 adds 60 days to the input value, checks to see if the calculated date is a non-work day (&Day = '1'), and if so, adds one day to the calculated date and tests again. When the calculated day is a work day (&Day = '0'), GREGTOLIL formats the date, displays it, and ends.

 

If we now CALL GREGTOLIL3 with the parameter '20080325', we will see the message 05/26/2008. As we know from our earlier discussion, this date is actually a holiday in the United States. Let's now CALL SETDAY with parameters ('20080526' *OFF). After this, CALL GREGTOLIL3 '20080325' results in the message 05/27/2008. If it was later decided that we would be working on Saturday, May 24, 2008, we could CALL SETDAY ('20080524' *WORK), and then CALL GREGTOLIL3 '20080325' would result in the message 05/24/2008. If, rather than finding the next work day, we wanted to calculate the previous work day, we simply subtract 1 instead of adding 1 when in the DoWhile loop. Pretty straightforward.

 

There are a few other benefits as well: As the CALENDAR entries are stored in a *USRSPC and accessed by a basing pointer, there is no duplication of the CALENDAR in each job accessing the CALENDAR entries. This also means that the instant SETDAY changes the &Status of a day, that change is immediately seen by all users of CALENDAR. There is no "loading" of the data as there would be with a database file containing the date information. And, as there is no database involved, we also don't have to worry about GREGTOLIL3 running into an end-of-file condition and being unable to read the entries anymore (though this CL consideration is lifted in V6R1).

 

But even more importantly, you've now seen how easy it can be to simulate an array and easily access entries within that array. Arrays, as we have seen here, can be much larger than what can be declared within CL for a *Char variable. Using *Based variables, as we did with &Day, we only need to define and use the (in this case) one byte that's currently important to us of the 94964-byte array. A very powerful tool has been added to your CL toolbox with the support for pointers and based variables in V5R4. I hope you can take advantage of this tool in your future application development.

 

More CL Questions?             

Wondering how to accomplish a function in CL? Send your CL-related questions to me at This email address is being protected from spambots. You need JavaScript enabled to view it.. I'll see what I can do about answering your burning questions in future columns.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: