Flashing Date in TXT to compare with Database Date

1

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?

    
asked by anonymous 12.05.2014 / 19:34

2 answers

4

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

    
12.05.2014 / 19:44
0

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);
    
12.05.2014 / 22:42