Convert month name to number in Delphi?

孤街浪徒 提交于 2019-12-29 09:17:20

问题


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


回答1:


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;



回答2:


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;


来源:https://stackoverflow.com/questions/13701100/convert-month-name-to-number-in-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!