22
Mon, Apr
1 New Articles

# Calculate Begin and End Dates for Any Month

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

Need to calculate the dates of the first and last days of last month or any month? See how easy it is in RPG IV.

It's fairly common that you need to calculate the dates of the first and last days of a month to print in report headings, show on screens, or select data. It is usually last month, but it could be next month or the last three months or whatever the customer requests. Date arithmetic in RPG IV makes it very easy to calculate past and future dates and date ranges. There are three simple rules, and it doesn't matter how you store dates.

Without RPG IV, typical "last month" logic might go something like this: To get the first of last month, split out year, month, and day using a data structure, force the day to 01, subtract one from the month, and if the result is zero, set month to 12 and subtract one from the year. To get the last day of last month, consult an array based on month, except if the month is 02; then you also have to figure out if this is a leap year, which is when the year is divisible by 4, but not divisible by 100, but is divisible by...and at that point my head begins to hurt! But help is at hand: RPG IV date arithmetic eliminates all this complexity. You can do it all in just two lines of code.

It's true that RPG IV date arithmetic must take place on date data types. What if you are saddled with legacy dates in packed or character fields? Not a problem; just check a previous article ("RPG IV Legacy Dates Cheat Sheet"), where I showed how easy it is to convert legacy dates to true dates and convert true dates back again, one statement for each direction. So with legacy dates, you might be up to four lines of code. Please keep reading.

First, I need to get into a little theory on how RPG IV handles date arithmetic.

RPG IV date arithmetic allows three durations to be added or subtracted from a date: days, months, and years. The logic in this article relies on the days and months durations. For clarity, I'm showing all example dates in ISO format, yyyy-mm-dd.

## Adding/Subtracting Days in RPV IV

Add or subtract a duration of one or more days to a date in RPV IV and you always get a valid date. The underlying logic is that the day always changes and the month and year change if necessary.

Examples:

•·                    2008-01-14 plus two days gives 2008-01-16. (Only the day changed.)

•·                    2008-02-29 plus one day is 2008-03-01. (The day and month changed. In addition, note that RPG IV knows that 2008 is a leap year.)

•·                    2007-12-31 plus one day is 2008-01-01. (Day, month, and year changed.)

Durations in months are a bit trickier, because there isn't always the same number of days in a month. What result would you expect if you add one month to 2008-01-01? I think most people would expect 2008-02-01 and that is what RPG IV provides.

But what should the result be if you add one month to 2008-01-30?  Hopefully no one is going to expect 2008-02-30, because that is an invalid date, even in a leap year. Some might expect 2008-03-01, given that January, where we started, has 31 days. RPG IV actually gives 2008-02-29. Why?

The logic with month durations is that the month always changes, the year changes if necessary, and the day doesn't change unless the result would be an invalid date, in which case the day is adjusted to the last day of the month. So, if you add one month to 2008-01-29, 2008-01-30, or 2008-01-31, the result is the same, 2008-02-29.

This leads to some perhaps non-intuitive situations where adding and subtracting the same duration doesn't get you back to where you started. For example, 2008-01-31 plus one month and then minus one month results in 2008-01-29.

The year duration rule is similar to the month rule. The year always changes, the month does not change, and the day changes only if the result is an invalid date. 2008-02-29 plus one year is 2009-02-28.

Enough of theory. How do you use date arithmetic to calculate month date ranges?

Rule 1

When using month durations, always work from the first of the month. As I'm sure you noticed above, the discrepancies come with dates at the end of the month.

Rule 2

To get to the first day of the month for any date, take the day of the month, subtract 1, and then subtract that many days from the date.

For example, if the date is 2008-03-02, then the day of the month is 02, so the start of the month is calculated as 2008-03-02 minus 02 - 1 days, which results in 2008-03-01. Similarly, if the date is 2008-03-21, then the start of the month is 2008-03-21 minus 21 - 1 days. This formula holds true for any date.

Rule 3

The first day of a month minus one month gives you the first day of the previous month. The first day of a month, minus one day, gives you the last day of the previous month. And that's all that is required to find the date range for last month.

## Practical RPG IV Code

Following is the RPG code to calculate first and last dates for last month, done step by step in four lines of code for clarity. If you need more details about any of the Built-in Functions (BIFs) used, check them in the RPG reference.

D A_Date          s               d

D WorkDays        S              3P 0

D MthBeg          s               d

D PrevMthEnd      s               d

D PrevMthBeg      s               d

/free

A_Date = %date('2008-03-17': *iso);

WorkDays = %subdt(A_Date: *days);

MthBeg = A_Date - %days(WorkDays -1);

PrevMthEnd = MthBeg - %days(1);

PrevMthBeg = MthBeg - %months(1);

Field A_Date is any date value. You could substitute %DATE() to use the current date. I'm setting it to St. Patrick's Day in 2008 for demonstration purposes.

The four steps/lines are straightforward:

1.                  WorkDays is calculated using the %subdt BIF to extract the day of the month: 17.

2.                  Subtract (WorkDays - 1) days from the A_Date to get MthBeg, the beginning of the month: 2008-03-01.

3.                  Subtract 1 day from MthBeg to get the PrevMthEnd, the last day of the previous month: 2008-02-29.

4.                  Subtract 1 month from MthBeg to get PrevMthBeg, the first day of the previous month: 2008-02-01.

You can just as easily do the calculation in two statements as I mentioned, without any intermediate fields:

PrevMthEnd = A_Date - %days(%subdt(A_Date: *days));

PrevMthBeg = PrevMthEnd  + %days(1) - %months(1);

It is not as intuitive because it isn't so obvious that we are doing all month durations from the first of the month.

Turns out to be simple and obvious, doesn't it, once someone points it out? Using this technique, starting with any date, you can find out the first and last dates of any month before it or after it.

## SQL

Incidentally, if you are into SQL, the same rules work there. Here's equivalent SQL:

A_Date - day(A_Date) days as PrevMthEnd,

A_Date - (day(A_Date) + 1) days - 1 months as PrevMthBeg

Use these constructions in a WHERE clause to select data. Substitute curdate() for A_Date if you want to calculate last month.

Sam Lennon is an analyst, developer, consultant and IBM i geek. He started his programming career in 360 assembly language on IBM mainframes, but moved to the AS400 platform in 1991 and has been an AS400/iSeries/i5/IBM i advocate ever since.

\$0.00 Raised:
\$

### Resource Center

• 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:

• More 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.

• 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:

• TRY 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.

• Forms 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.

• IT 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.

• Can 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:

• 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:

• Managing 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:

• The 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:

• For 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:

• 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.

• When 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:

• Supply 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

• 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.