Follow the code:
dtcompra := copy(lTemp,65,2)+'-'+copy(lTemp,63,2)+'-'+copy(lTemp,58,4);
if
DModuleGrid.ZQuery1.ParamByName('dtcompra').AsDateTime = StrToDateTime(dtcompra)
then
begin
//codigo
end;
Any tips on improving the code?
Follow the code:
dtcompra := copy(lTemp,65,2)+'-'+copy(lTemp,63,2)+'-'+copy(lTemp,58,4);
if
DModuleGrid.ZQuery1.ParamByName('dtcompra').AsDateTime = StrToDateTime(dtcompra)
then
begin
//codigo
end;
Any tips on improving the code?
I'd rather protect the data to avoid unexpected exceptions, so I'd do it like this:
//Pega a data do arquivo texto
dtCompraTxt := copy(lTemp,65,2)+'/'+copy(lTemp,63,2)+'/'+copy(lTemp,58,4);
//Tenta converter a data em texto para tipo TDateTime, se não conseguir lança exceção
if not TryStrToDateTime(dtCompraTxt, dtCompra) then
raise EConvertError.CreateFmt('A data do arquivo ("%s") não é uma data válida.', [dtCompraTxt]);
//Realiza a comparação das datas com SameDate da unit DateUtils
if SameDate(DModuleGrid.ZQuery1.ParamByName('dtcompra').AsDateTime, dtCompra) then
begin
end;
SameDate documentation on this link
>Note: This will only compare date and not hour minutes and seconds
The problem with this approach is that the regional settings of your user's operating system may not match the format of the string you have in TXT.
For example:
If your date string is: 01-12-2014 (December 1) and the user's windows is set to English, the date will be interpreted as being "January 12" .
To avoid this problem, use the StrToDateTime method, passing TFormatSettings
var
AFormatSettings: TFormatSettings;
dtcompra : TDateTime;
begin
AFormatSettings:=TFormatSettings.Create;
AFormatSettings.ShortDateFormat:='dd-mm-yyyy';
AFormatSettings.DateSeparator:='-';
dtcompra := StrToDateTime('01-12-2014', AFormatSettings);