Convert month name to number in Delphi?

2019-01-29 06:48发布

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条回答
等我变得足够好
2楼-- · 2019-01-29 06:59

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;
查看更多
干净又极端
3楼-- · 2019-01-29 07:20

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;
查看更多
登录 后发表回答