How to find the last day of the month

Chris Kelleher

Administrator
Staff member
<BLOCKQUOTE><font size="1" face="Arial, Verdana">code:</font><HR><pre>def var Vdate as date FORMAT "99/99/9999" no-undo.
def var Vlast as date FORMAT "99/99/9999" no-undo.

REPEAT:
update vdate.

run get_last_day (INPUT Vdate, OUTPUT Vlast).

disp Vdate Vlast.
END. /* repeat */

PROCEDURE get_last_day :
DEFINE INPUT PARAMETER Vdate AS DATE NO-UNDO.
DEFINE OUTPUT PARAMETER Vlast AS DATE NO-UNDO.

IF MONTH(VDate) NE 12 THEN
Vlast = DATE( MONTH(Vdate) + 1 , 1, YEAR(Vdate)) - 1.
ELSE
Vlast = DATE( 1 , 1, YEAR(Vdate) + 1) - 1.
END.
/* end of sample.p */[/code]
 

Rutger

New Member
I have a different solution for this..

Code:
DEFINE VARIABLE v-dat		 AS DATE	 NO-UNDO.
DEFINE VARIABLE v-dat_lst_mth AS DATE	 NO-UNDO.
 
REPEAT:
   UPDATE v-dat.
   RUN Get_Last_Day (INPUT v-dat, OUTPUT v-dat_lst_mth).
   MESSAGE v-dat_lst_mth
	  VIEW-AS ALERT-BOX INFO BUTTONS OK.
END.
 
PROCEDURE Get_Last_Day :
   DEFINE INPUT PARAMETER i-dat AS DATE	 NO-UNDO.
   DEFINE OUTPUT PARAMETER o-dat_lst_mth AS DATE	 NO-UNDO. 
   DEFINE VARIABLE v-day_lst AS INTEGER NO-UNDO INIT 31.
 
   ASSIGN o-dat_lst_mth = DATE(MONTH(i-dat),v-day_lst, YEAR(i-dat)) NO-ERROR.
 
   REPEAT WHILE ERROR-STATUS:ERROR:
	  ASSIGN
		 v-day_lst = v-day_lst - 1
		 o-dat_lst_mth = DATE(MONTH(i-dat),v-day_lst, YEAR(i-dat)) NO-ERROR.	 
   END.
END.

I have the experience that using less substractions etc make the code better readable and understandable for other programmers.
 
FWIW, my personal favourite is

function Get_Last_Day returns DATE
(input v-date as date):
def var v-last as date no-undo.
assign v-last = (date(month(v-date), 28, year(v-date)) + 4)
v-last = v-last - day(v-last).
return v-last.
end.

Short, sharp and uses Progress native date arithmetic!
 

ovf

Member
An other option:

function get-last-date returns date (input v-date as date):
define variable r-date as date no-undo.

/* Place r-date somewhere in next month */
r-date = v-date - day(v-date) + 32.

/* Return last date in this month */
return r-date - day(r-date).
end.

Ole
 
Top