Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi StrToDate not accepting date [duplicate]

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;
like image 592
Rudi Thiel Avatar asked Feb 01 '26 12:02

Rudi Thiel


1 Answers

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;
like image 198
Remy Lebeau Avatar answered Feb 04 '26 06:02

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!