[Lazarus] StrToDate and DefaultFormatSettings

Howard Page-Clark hdpc at talktalk.net
Fri Sep 12 17:16:53 CEST 2014


On 12/09/2014 13:04, Henry Vermaak wrote:
> On Fri, Sep 12, 2014 at 08:18:36AM -0300, "Leonardo M. Ramé" wrote:
>> Hi, I need to convert strings with format "d-mmm-y" to TDateTime.
>>
>> For example: '12-Sep-14'

This will accomplish the task.

function DatestrToDateTime(const aDate: string): TDateTime;
const
   sep = '-';
var
   el, p, im, id, iy: integer;
   d, m, y: word;
   dt: string;

   function FindMatch(const aMon: string): integer;
   var
     i: integer;
   begin
     DebugLn(['aMon=',aMon]);
     Result:=-1;
     for i:=Low(TMonthNameArray) to High(TMonthNameArray) do
      if SameText(aMon, DefaultFormatSettings.ShortMonthNames[i]) then begin
        Result:=i;
        Break;
      end;
   end;

begin
   dt:=Trim(aDate);
   el:=Length(dt);
   if (el < 7) or (el > 11) then
     Exit(0.0);

   p:=Pos(sep, aDate);
   if (p=0) or (not TryStrToInt(Copy(dt, 1, p-1), id)) then
     Exit(0.0);
   Delete(dt, 1, p);
   p:=Pos(sep, dt);
   if (p=0) then
     Exit(0.0);

   im:=FindMatch(Copy(dt, 1, p-1));
   if (im < 1) then
     Exit(0.0)
   else m:=im;

   Delete(dt, 1, p);
   if not TryStrToInt(dt, iy) then
     Exit(0.0);
   d:=id;

   if (iy < 2000) then
     Inc(iy, 2000);
   y:=iy;
   if not TryEncodeDate(y, m, d, Result) then
     Result:=0.0;
end;





More information about the Lazarus mailing list