Date Killing in TXT to compare with Database Date

Asked

Viewed 142 times

1

Follows 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 hint of improving the code?

2 answers

4


I prefer to protect the data to avoid unexpected exceptions, so I would do so:

//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;

Documentation about Samedate in this link

Obs.: Thus it will be compared only date and not hour minutes and seconds

  • It has a simpler way and do it, so I understand well how the sql and Delphi function works.

  • I added some comments, I don’t know if this is what you wanted

0

the problem in this approach is that your user’s regional operating system settings 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 method Strtodatetime, passing by Tformatsettings

var
  AFormatSettings: TFormatSettings;
  dtcompra  : TDateTime;
begin
   AFormatSettings:=TFormatSettings.Create;
   AFormatSettings.ShortDateFormat:='dd-mm-yyyy';
   AFormatSettings.DateSeparator:='-';
   dtcompra  :=  StrToDateTime('01-12-2014', AFormatSettings);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.