Convert month name to number in Delphi?

后端 未结 2 1345
时光说笑
时光说笑 2020-12-21 20:34

Is there some built-in Delphi (XE2)/Windows method to convert month names to numbers 1-12; instead of looping through (TFormatSettings.)LongMonthNames[] myself?

相关标签:
2条回答
  • 2020-12-21 20:43

    i can't find a method but i write one. ;-)

    function GetMonthNumberofName(AMonth: String): Integer;
    var
      intLoop: Integer;
    begin
      Result:= -1;
      if (not AMonth.IsEmpty) then
      begin
        for intLoop := Low(System.SysUtils.FormatSettings.LongMonthNames) to High(System.SysUtils.FormatSettings.LongMonthNames) do
        begin
          //if System.SysUtils.FormatSettings.LongMonthNames[intLoop]=AMonth then  --> see comment about Case insensitive
          if SameText(System.SysUtils.FormatSettings.LongMonthNames[intLoop], AMonth) then
          begin
            Result:= Intloop;
            Exit
          end;
        end;
      end;
    end;
    

    Ok, I change this function for other FormatSettings.

    function GetMonthNumberofName(AMonth: String): Integer; overload;
    function GetMonthNumberofName(AMonth: String; AFormatSettings: TFormatSettings): Integer; overload;
    
    function GetMonthNumberofName(AMonth: String): Integer;
    begin
      Result:= GetMonthNumberofName(AMonth, System.SysUtils.FormatSettings);
    end;
    
    function GetMonthNumberofName(AMonth: String; AFormatSettings: TFormatSettings): Integer;
    var
      intLoop: Integer;
    begin
      Result:= -1;
      if (not AMonth.IsEmpty) then
      begin
        for intLoop := Low(AFormatSettings.LongMonthNames) to High(AFormatSettings.LongMonthNames) do
        begin
          if SameText(AFormatSettings.LongMonthNames[intLoop], AMonth) then
          begin
            Result:= Intloop;
            Exit
          end;
        end;
      end;
    end;
    

    Call the function with the system formatsetting

    GetMonthNumberofName('may');
    

    or with FormatSetting

    procedure TForm1.Button4Click(Sender: TObject);
    var
      iMonth: Integer;
      oSettings:TFormatSettings;
    begin
      // Ned
      // oSettings:= TFormatSettings.Create(2067);
      // Fr
      // oSettings:= TFormatSettings.Create(1036);
      // Eng
      oSettings:= TFormatSettings.Create(2057);
      iMonth:= GetMonthNumberofName(self.Edit1.Text, oSettings);
      showmessage(IntToStr(iMonth));
    end;
    
    0 讨论(0)
  • 2020-12-21 20:53

    You can use IndexStr from StrUtils, returns -1 if string not found e.g.

    Caption := IntToStr(
      IndexStr(FormatSettings.LongMonthNames[7], FormatSettings.LongMonthNames) + 1);
    

    EDIT:
    To avoid problems with casting and case sensitivity you might use IndexText as shown:

    Function GetMonthNumber(Const Month:String):Integer; overload;
    begin
       Result := IndexText(Month,FormatSettings.LongMonthNames)+1
    end;
    
    0 讨论(0)
提交回复
热议问题