Link to home
Start Free TrialLog in
Avatar of henryreynolds
henryreynoldsFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Delphi Get previous month and year

Good day

What is the best way of getting the previous month and year.

example current month and year 201001

should be 200912

and 201005 should be 201004
Avatar of twinsoft
twinsoft
Flag of Greece image

Hi, this is the easiest way to do it

procedure TForm1.Button1Click(Sender: TObject);
begin
 ShowMessage(DateToStr(IncMonth(now, -1)));
end;

This will get a date with previous month. If you want previous year substract 12 months
ASKER CERTIFIED SOLUTION
Avatar of twinsoft
twinsoft
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mahdi78
If you want to use you date format, try this

function GetPreviousDate(IntDate: Integer): string;
var Year, Month: word;
begin
Year := StrToInt(Copy(IntToStr(IntDate), 1, 4));
Month := StrToInt(Copy(IntToStr(intDate), 5, 2));
if Month = 1 then result := IntToStr(Year - 1) + '12'
else result := IntTostr(year) + IntToStr(Month - 1);
end;

procedure TForm1.Button1Click(Sender: TObject);

begin
showmessage(GetPreviousDate(201001)) ;
end;
It appears that, although you said you wanted the "previous month and year", you actually want the previous month and, if the current month is January, you want December of the previous year.
 In that case, twinsoft's solution is the correct one.
Now, if you want to be able to do something like display the year in one TEdit control and the month in another and then selectively either subtract one year or one month, you can accomplish that with the following code.
 

procedure TForm1.SubtractYearClick(Sender: TObject);
begin
 ShowMessage(DateToStr(IncYear(now, -1)));
end;

procedure TForm1.SubtractMonthClick(Sender: TObject);
begin
 ShowMessage(DateToStr(IncMonth(now, -1)));
end;

Open in new window

@henryreynolds

If I read your question correctly, you have a string that contains yyyymm value and you need to calculate/output the yyyymm value for the prior month.

First, you will need to convert your yyyymm sting into a date, using the first day of the month as a default.  Then pass that date value to a version of the twinsoft routine (from http:#28531199).
IncMonth(converteddatevalue, -1)

Next, you will need to format that prior month's date back into yyyymm format.
Avatar of henryreynolds

ASKER

Thank you very much
@ henryreynolds

Are you sure you meant to accept that comment and not the one above it?