[Delphi] Delphi StrToDate函数抛错: ''yyyy-mm-dd'' is not a valid date'

StrToDate()

function StrToDate(const S: string): TDateTime;
function StrToDate(const S: string; const FormatSettings: TFormatSettings): TDateTime;

StrToDate将给定的字符串转换为日期值。 分隔符只能是为'' / '', eg: '2019-10-01', 年值假定在本世纪为0到99之间。 给定字符串只能包含有效日期。 如分隔符不是'' / '', 如''2010-12-1'', 此时抛错: ''2010-12-1'' is not a valid date'.为解决此函数固定分隔符的问题。可构造 FormatDateStrt函数。

function FormatDateStr(s: string):TDateTime;
var
  y, m, d, i: Integer;
  delimitor: string;
begin  
  s := Trim(s); 

  if (Length(s) > 10) or (Length(s) < 8)then begin
    RaiseException('!'); //根据自己需求创建Exception
  end;   
  
  for i := 1 to Length(s) do begin
  	if not (s[i] in ['0'..'9']) then begin 
  		delimitor := s[i];
  		break;
  	end;
  end;            
  y := StrToInt(fetch(s, delimitor));    //利用fetch copy pos等函数实现
  m := StrToInt(fetch(s, delimitor));
  d := StrToInt(fetch(s, delimitor)); 
  Result := EncodeDate(y, m, d);
end;

未完待续
原文地址:https://www.cnblogs.com/xianeri/p/11674042.html