1

是否有一些内置的 Delphi (XE2)/Windows 方法可以将月份名称转换为数字 1-12;而不是循环通过(TFormatSettings.)LongMonthNames[]自己?

4

2 回答 2

7

您可以使用IndexStrfrom ,如果找不到字符串则StrUtils返回,例如-1

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

编辑:
为了避免转换和区分大小写的问题,您可以使用IndexText如下所示:

Function GetMonthNumber(Const Month:String):Integer; overload;
begin
   Result := IndexText(Month,FormatSettings.LongMonthNames)+1
end;
于 2012-12-04T11:07:24.947 回答
0

我找不到方法,但我写了一个。;-)

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;

好的,我将此功能更改为其他格式设置。

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;

使用系统格式设置调用函数

GetMonthNumberofName('may');

或使用 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;
于 2014-01-20T10:25:54.530 回答