delphi-4

Obtain YYYYMM String from Now in Delphi 4


I want to obtain an string 'YYYYMM' from Now procedure and from the month before the current one in Delphi 4.

For example: 202106 (Now) and 202105 (Now - 1)

How can afford that?


Solution

  • You can use DecodeDate to split a TDateTime - like Now - into year, month and day parts. Then you can use Format to create the string with a 4 digits year and month as 2 digits with leading zeros:

    var
        Year, Month, Day: Word;
        Today     : TDateTime;
        Yesterday : TDateTime;
        SToday     : String;
        SYesterday : String;
    begin
        Today     := Now;
        Yesterday := Today - 1;
    
        DecodeDate(Today, Year, Month, Day);
        SToday := Format('%04d%02d', [Year, Month]);
    
        DecodeDate(Yesterday, Year, Month, Day);
        SYesterday := Format('%04d%02d', [Year, Month]);
    end;