TechTricks
Technical answers from the trenches 
 
 
 
 

     
   
Determining the Last Day of a Month
 
   
 Posted: 1 April 2002
 
   
Submitted by Kathy M. 
 Applies to: All versions
 
   
 
Audience: Intermediate
 
       
   

Question: I'm trying to determine the last day of a month, but am finding it difficult to implement all the rules associated with the different months, leap years, and so on. Isn't there an easy way to do this?

Actually, there is. Determine the first day of the next month and then subtract one day, as shown in the following code sample:

function getLastDay( dtADate : TDateTime ) : TDateTime;
// ---------------------------------------------------------
// When passed a value TDateTime, returns the last day of
// the month it refers to.  Note: Default exception handling
// of bad dates has not been overridden.  GIGO.
// ---------------------------------------------------------
var
   wYY, wMM, wDD : Word;      // Year, Month, & Day of input
begin

   decodeDate( dtADate, wYY, wMM, wDD );
   inc( wMM );
   if ( wMM = 12 ) then
   begin
      wMM := 1;
      inc( wYY );
   end;
   result := encodeDate( wYY, wMM, 01 ) - 1;

end;

As you can probably tell, the above sample provides a convenient function that does this for you. Use something like this to call it:

procedure TForm1.Button3Click(Sender: TObject);
var
   strLastDay : String;
begin

   strLastDay := DateTimeToStr( getLastDay( sysUtils.Date ) );
   application.MessageBox( pChar( strLastDay +
      ' is the last day of the current month.' ) ,
      'FYI', mb_OK );

end;

Tip: Because Date() and Time() are commonly used terms, it's a good idea to specifically qualify references to the functions in the SYSUTILS unit, as shown in the last code sample. This may help prevent confusion in the long run.

 

       

Top

Feedback About Paradox Delphi Assorted Web Stuff
 
 
Copyright © 2000-2004, techtricks.com; All Rights Reserved.
Acknowledgements, Disclaimers, Terms and Conditions.
Article last updated on 31 May 2003

 

Other Sites: Paradox, Delphi, Perl, Web Stuff, and More


 

[- End -]