Delphi StrToDate not accepting date

11.5k Views Asked by At

I am trying to convert a date from string to TDate by using the StrToDate method, however when I pass a date to it in the format yyyy/mm/dd it gives me this error: '''2013/11/12'' is not a valid date'. Any ideas what I'm doing wrong? Thanks

var
  newDate: TDate;
begin
  newDate := StrToDate(sDate);
end;
1

There are 1 best solutions below

2
On BEST ANSWER

The overloaded version of StrToDate() that takes only a string as input uses the user's default locale settings from the OS. The error means the string does not match the user's locale format for dates.

Use the overloaded version of StrToDate() that accepts a TFormatSettings as input so you can specify the desired format:

var
  newDate: TDate;
  fmt: TFormatSettings;
begin
  // TFormatSettings.Create() was added in XE
  // and GetLocaleFormatSettings() was deprecated
  //
  // fmt := TFormatSettings.Create;
  GetLocaleFormatSettings(0, fmt);

  fmt.ShortDateFormat := 'yyyy/mm/dd';
  fmt.DateSeparator := '/';

  newDate := StrToDate(sDate, fmt);
end;