在Delphi中将月份名称转换为数字?

时间:2012-12-04 10:43:27

标签: delphi date-parsing

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

2 个答案:

答案 0 :(得分:7)

您可以使用IndexStr中的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;

答案 1 :(得分: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;

好的,我为其他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;

使用系统格式设置

调用该函数
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;