02
Sat, Nov
2 New Articles

Determining End of the Month

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times
You'd think with Y2K long since gone, we wouldn't care about date routines. What I have found, however, is that when I teach RPG IV, I get very good feedback for some of the date routines that I have written over the last few years using native RPG IV opcodes and OS/400 date APIs.

The ability to retrieve the date of the last day of the month has been a long-standing issue with developers--years of compile-time tables with that strange number in them: 312831303130313130313031. And what happens during a leap year?

Using this kind of routine today is as reliable as using a ceramic drain tile. It'll last a while, but it's too dependent on conditions being static into the foreseeable future.

Like the PVC piping we use in our homes today, the more modern RPG constructs are designed to be easier to use and long-lasting. Today, we use the built-in operation codes and OS/400 APIs that support integrated date processing.

The built-in date operation codes that support date manipulation that I use most include the following:

  • TEST--Test a field for a valid date or time value
  • ADDDUR--Add a period of time to an existing date, time, or timestamp value
  • SUBDUR--Subtract a period of time from an existing date or time field, or calculate the period of time between two date or time values

The EXTRCT (extract) operation code is also useful, but I rarely use it. In fact, I can only think of one instance where I used it--in the development of this issue's ENDOFMONTH procedure. The EXTRCT opcode (strangely spelled wrong on purpose by IBM) extracts a component of a date or time field. So if you need to know what the day is in a date field, you extract the day using EXTRCT.

The TEST opcode is very cool. It checks a field for a valid date or time value. The field's data type can be character, numeric, date, time, or timestamp. The TEST opcode supports several operation extenders:

  • DE--Check for a valid date value
  • TE--Check for a valid time value
  • ZE--Check for a valid timestamp value

The DE operation extender is used when checking a non-date field for a valid date value. Also, Factor 1 of the TEST opcode must contain the format of the data in the field being tested. For example, if the value in the Result field is in MDY format, *MDY would be specified in Factor 1. Figure 1 shows the code you'd use to check a non-date field for a valid date value. Similar support is provided for time and timestamp values using the TE and ZE operation extenders.

0001 C     *MDY          TEST(DE)                in_Date
0002 C                   if        %ERROR
0003 C*                   // do something useful here.
0004 C                   endif

Figure 1: Testing a non-date field for a date value

The E operation extender is all that's needed for true date or time data-type fields. Because these fields are already known to the program as date fields, you don't have to tell the TEST opcode what you're checking the fields for. Also, since the DATFMT keyword has specified the data format, specifying the format in Factor 1 would be redundant and is, therefore, not allowed. Figure 2 shows the code you'd use to check a date field for a valid date value.

0001 C                   TEST(E)                 dueDate
0002 C                   if        %ERROR
0003 C*                   // do something useful here.
0004 C                   endif

Figure 2: Testing a date field for a date value

The syntax of the TEST opcode can be confusing because of a few benign restrictions placed on it. When a non-date or non-time data-type field is being tested, you must specify the corresponding D, T, or Z operation extender. This makes perfect sense. However, when you specify a true data, time, or timestamp data-type, you cannot specify the D, T, or Z operation extender--not even the correct one. So for example, Figure 3 would produce a compile-time error:

.....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++
0001 D dueDate         S               D   Inz(D'1969-07-20')
.....CSRn01Factor1+++++++OpCode(ex)Factor2+++++++Result++++++++
0002 C     *ISO          TEST(DE)                dueDate

Figure 3: Invalid TEST opcode syntax

What's wrong with this picture? Nothing in my mind, but the compiler doesn't like anything specified in Factor 1 when a real date, time, or timestamp value is being tested. It also doesn't like the operation extender being specified. So only the Error extender (E) can be specified.

When I'm teaching RPG IV, I find this point always perplexes the students. Why not allow both Factor 1 and the operation extender when the Result field is a valid date, time, or timestamp field? After all, the compiler allows you to specify the length of a date field and gives you an error only if the length is wrong. You can't set the length of a data field, so specifying a length is as redundant as specifying the D operation extender. I can't explain the logic behind these requirements. It's just a fact that we have to accept.

The E operation extender is required in order to avoid using response indicators. That is, the %ERROR built-in function only reacts to opcodes that use the E operation extender (don't get me started on why I think that was a questionable design decision). So if you omit the E operation extender, %ERROR will not reflect the results of the TEST operation code.

The ADDDUR (add duration) operation code allows you to add a period of time to a date, time, or timestamp value. The period of time is specified as the duration. You specify the duration in Factor 2 followed by a duration code. The duration code tells the compiler (actually, it tells the opcode) what you're adding to the date field. Are you adding days, months, years? Whatever it is, it is specified in Factor 2 along with the duration itself.

The SUBDUR (subtract duration) operation code allows you to do either of the following:

  1. Subtract a period of time from a date, time, or timestamp value. The period of time is specified as the duration. You specify the duration in Factor 2 followed by a duration code. The duration code tells the compiler what it is that is being subtracted from the field.
  2. Calculate the duration between two date data-type values (date, time, or timestamp). The result is the duration between the two values and is specified in the Result field followed by the duration code. In this form of the opcode, the duration code indicates the number of days, months, years, hours, minutes, or seconds between two values. You specify which one of these you want by placing the duration code adjacent to the field name in the Result field.

One of the greatest things that SUBDUR does is calculate the number of days between two date values. Just this one, accurate feature provides a level of productivity that I would have loved to see back in the early days of RPG III.

Duration codes are, for the most part, self-explanatory and include those shown in Figure 4:

Duration Code
Alternative Short Form
*DAYS
*D
*MONTHS
*M
*YEARS
*Y
*HOURS
*H
*MINUTES
*MN
*SECONDS
*S
*MSECONDS
(microseconds)
*MS

Figure 4: ADDDUR and SUBDUR duration codes

Either form of the duration code may be specified for the ADDDUR and SUBDUR operation codes. Please note that, unlike *ZERO and *ZEROS or *BLANK and *BLANKS, only the singular form of the duration codes is provided.

ENDOFMONTH Procedure

To illustrate the use of all these integrated date and time operation codes, I came up with a procedure that performs an important task. I've always needed the ability to calculate the last day of the month, given the current date. The ENDOFMONTH procedure does just that. Given a date as input, ENDOFMONTH calculates the last date of the month for the input date.

end-of-month = EndOfMonth( myDate )

The ENDOFMONTH procedure accepts any valid date value or field as input (in any date format). The return value is a valid date value (*ISO format) that may be assigned to any date data-type variable (in any date format). The return value is the date of the end of the month calculated by the input date.

For example, if the input date is January 29, 2002, the date that is returned will be January 31, 2002. Figure 5 contains the source code for the ENDOFMONTH procedure. Figure 6 shows the ENDOFMONTH procedure prototype. As always, you can look for updates or fixes to this or any other source I've published in Midrange Developer by viewing the related discussion forum for any given article.

0001 P EndOfMonth      B                   Export 
.....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++
0002 D EndOfMonth      PI              D   DatFmt(*ISO)
0003 D  in_Date                        D   Const DatFmt(*ISO)

     ** Local variable begin here
0004 D NextMth         S               D   DatFmt(*ISO)
0005 D nDay            S              5I 0
0006 D EndOfMth        S               D   DatFmt(*ISO)

.....CSRn01Factor1+++++++Opcode(ex)Factor2+++++++Result+++++
0007 C                   TEST(E)                 in_Date
0008 C                   if        %ERROR
0009 C                   return    D'0001-01-01'
0010 C                   endif

.... CSRn01Factor1+++++++Opcode(ex)Factor2+++++++Result+++++
0011 C     in_Date       AddDur    1:*Months     NextMth
0012 C                   Extrct    NextMth:*Days nDay
0013 C     NextMth       SubDur    nDay:*Days    EndOfMth
0014 C                   return    EndOfMth
0015 P EndOfMonth      E

Figure 5: ENDOFMONTH Procedure Implementation

.....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++
     ** ENDOFMONTH Prototype 
0001 D EndOfMonth      PR              D   DatFmt(*ISO)
0002 D  in_Date                        D   Const DatFmt(*ISO)

Figure 6: ENDOFMONTH Procedure Prototype

BOB COZZI

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.


MC Press books written by Robert Cozzi available now on the MC Press Bookstore.

RPG TnT RPG TnT
Get this jam-packed resource of quick, easy-to-implement RPG tips!
List Price $65.00

Now On Sale

The Modern RPG IV Language The Modern RPG IV Language
Cozzi on everything RPG! What more could you want?
List Price $99.95

Now On Sale

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: