Reputation: 71
I am unable to convert my string format date (French) to TDateTime
format. I am working on files which contain string format dates in English and other languages.
For example, 1st March 2021 will be in an English file as 1 mar 2021
, and in a French file as 1 mars 2021
.
var
_StrDate: String;
_MyDateTime: TDateTime;
begin
_StrDate := '1 mar 2021'; // English
_MyDateTime := VarToDateTime(_StrDate); // works perfect
_StrDate := '1 mars 2021'; // French
_MyDateTime := VarToDateTime(_StrDate); // error
end;
I'm getting this error msg:
Could not convert variant of type (UnicodeString) into type (Date)
Upvotes: 1
Views: 1166
Reputation: 12292
I wrote a parser for the specific format your have. Well, I have done the basic work, you'll have to modify it for example to use both French and English month names as well as short names. You should also add some tests to filter invalid values out. And probably ignore character casing in the name of months.
const
MonthsFR : array [1..12] of String = (
'janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet',
'août', 'septembre', 'octobre', 'novembre', 'décembre');
function StrToDateFR(const S : String; out ADate : TDateTime) : Boolean;
var
A : TStringDynArray;
D : Word;
M : Word;
Y : Word;
begin
ADate := 0;
Result := FALSE;
A := SplitString(S, ' ');
if Length(A) <> 3 then
Exit;
D := StrToInt(A[0]);
M := High(MonthsFR);
while (M > Low(MonthsFR)) and (A[1] <> MonthsFR[M]) do
Dec(M);
if M < Low(MonthsFR) then
Exit;
Y := StrToInt(A[2]);
ADate := EncodeDate(Y, M, D);
Result := TRUE;
end;
One idea to expand the code is to have several similar functions for other languages. Since the function return TRUE only when the format is recognized, you may call various versions in sequence until one return true.
Upvotes: 3
Reputation: 71
function StrToDateFR(const S: String; out ADate: TDateTime): Boolean;
var
A: TStringDynArray;
D: Word;
M: Word;
Y: Word;
i: integer;
begin
ADate := 0;
Result := FALSE;
A := SplitString(S, ' ');
if Length(A) <> 3 then
Exit;
D := StrToInt(A[0]);
M := 0;
for i := Low(MonthsFR) to High(MonthsFR) do
begin
if SameText(A[1], MonthsFR[i]) then
begin
M := i;
Break
end;
end;
if M = 0 then
Exit;
Y := StrToInt(A[2]);
ADate := EncodeDate(Y, M, D);
Result := TRUE;
end;
Upvotes: 0