Link to home
Start Free TrialLog in
Avatar of Zsolt
ZsoltFlag for Hungary

asked on

Delphi: StrToDate function raises not a valid date

Hello,
The following code raises  this exception:

 raised exception class EConvertError with message ''2022.03.12.' is not a valid date'.


  FormatSettings.ShortDateFormat := 'yyyy.mm.dd';
  FormatSettings.DateSeparator := '.';
...
if StrToDate(FieldByName('MyDate').AsString) <> Date Then  
 Begin
  ...

Open in new window

I don't understand why because I set FormatSettings.ShortDateFormat to correct format before calling StrToDate.
Then I changed the code to this:


  var F: TFormatSettings;
  F.ShortDateFormat := 'yyyy.mm.dd';
  F.DateSeparator := '.';

...
if StrToDate(FieldByName('MyDate').AsString,F) <> Date Then  //,fs
             Begin

Open in new window

... and I supposed that it would work but it gives me the same error.

It is Windows 10 operation system, the Windows language is English, but Regional settings are set to Hungarian.


Thank you.


Avatar of Ferruccio Accalai
Ferruccio Accalai
Flag of Italy image

I've tested it on my Italian settings and it works fine. Are you sure about the MyDate field content?
Anyway check the localsetting before to change the formatsettings to see how is set by the system

var
  F: TFormatSettings;
begin
  GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, f);

Open in new window

Is there a reason you are storing dates as string values? That is not overly portable and likely to cause you problems like this. If the underlying database field is a date type, could you not just use the .asDate property in your comparison code?

Is it possible that your date field is null, which would result in .asString being an empty string? This would fail any checks for being a valid date.
ASKER CERTIFIED SOLUTION
Avatar of Ferruccio Accalai
Ferruccio Accalai
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial