Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Display last months date in DateTimePicker 2

Status
Not open for further replies.

AP81

Programmer
Apr 11, 2003
740
AU
I am trying to display last months date (from the current date) in a date time picker control.

This is what I have used:

lastMonth := DateToStr(date);
lastMonth := Copy(lastmonth, 1, 3) +
IntToStr(intMonth) + '/' +
Copy(lastmonth, 7,4);

However, doesn't always work correctly. Is there a better way?




------------------------------------
There's no place like 127.0.0.1
------------------------------------
 
Try this:

Make sure the USES clause has [tt]DateUtils[/tt] added.
Then in your procedure/function....

Code:
var
  nMonth, nYear, nDay : word;
begin
  nMonth := MonthOf(mydate);  // work out what month we are in and go back 1
  nYear := YearOf(mydate);
  nDay := DayOf(mydate);
  if nMonth = 1 then
    begin // adjust for year if needed
      nMonth := 12;
      dec(nYear);
    end
  else
    begin
      dec(nMonth);
    end;           // set the datesstartup

  DT_Picker.Date := EncodeDate(nYear,nMonth,nDay);
end;

Hope that helps

Cheers


Chris ;-)
 
Oops....

Forgot to mention that you should check that the nDay value is valid - ie can't have 31-Feb-2004

You can use the other functions in DateUtils to check a lot of these. Use the function
[tt]
bValidDate := IsValidDateTime(nYear, nMonth, nDay, 0,0,0,0);
[/tt]
prior to the EncodeDate. If its true, do it, or else adjust the date using [tt]EndOfAMonth[/tt] function
The zeros are Hours,Minutes,Seconds,Milliseconds


Chris ;-)
 
Thanks. Works.




------------------------------------
There's no place like 127.0.0.1
------------------------------------
 
Much easier is to use the IncMonth function that is in SysUtils:
Code:
  DT_Picker.Date := IncMonth ( Now, -1 );

Andrew
Hampshire, UK
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top