Search code examples
delphidelphi-12-athens

How to convert month number to month name in Delphi?


I found a question asking "Convert month name to number in Delphi?".

What's the easiest/best way to do the opposite of that?

I want to get the month name from the month number. Is there a built-in function for this in Delphi?

I want something like a function where I can pass in the month number and get back the name for the month or perhaps even a function where I pass in a TDate and get back the month name for that TDate.

Is there something like this in Delphi Programming?

I know I can do a bunch of if statements and return the literal string for each month number, but is that really the best/easiest way?


For my use case, I only need it to be in English and the full month name.


Solution

  • Here is a simple program to demonstrate one way to do what you want:

    {$APPTYPE CONSOLE}
    
    uses
      System.SysUtils;
    
    var
      FormatSettings_en_us: TFormatSettings;
    
    procedure Main;
    var
      MonthIndex: Integer;
    begin
      for MonthIndex := 1 to 12 do begin
        Writeln(FormatSettings_en_us.LongMonthNames[MonthIndex]);
      end;
    end;
    
    begin
      FormatSettings_en_us := TFormatSettings.Create('en-us');
      try
        Main;
      except
        on E: Exception do
          Writeln(E.ClassName, ': ', E.Message);
      end;
      Readln;
    end.
    

    I've specified US English locale because that's what you asked for in the question. But of course you could use different locales, or not specify a locale in which case the user's locale would be used.