'23/02/2011 12:34:56'无效的日期和时间

ste*_*ve0 16 delphi

在我的代码中,我遇到了一个问题.示例代码:

var 
    d1: tdatetime
begin
    d1 := strtodatetime('23/02/2011 12:34:56');
end; 
Run Code Online (Sandbox Code Playgroud)

但它给出了错误:

'23/02/2011 12:34:56'无效的日期和时间

我在做什么有什么问题?

RRU*_*RUZ 36

StrToDateTime函数使用ShortDateFormat,并DateSeparator在日期部分和转换LongTimeFormat,并TimeSeparator以部分时间.所以你的字符串必须与这些变量匹配才能将字符串转换为TDateTime.相反,你可以使用带TFormatSettings参数的StrToDateTime 来解析你的字符串.

 function StrToDateTime(const S: string; const FormatSettings: TFormatSettings): TDateTime; 
Run Code Online (Sandbox Code Playgroud)

检查这个样本

Var
StrDate : string;
Fmt     : TFormatSettings;
dt      : TDateTime;
begin
fmt.ShortDateFormat:='dd/mm/yyyy';
fmt.DateSeparator  :='/';
fmt.LongTimeFormat :='hh:nn:ss';
fmt.TimeSeparator  :=':';
StrDate:='23/02/2011 12:34:56';
dt:=StrToDateTime(StrDate,Fmt);
Run Code Online (Sandbox Code Playgroud)

  • 因为_nn_表示分钟而_mm_表示月份. (2认同)

Kro*_*ica 9

使用VarToDateTime可能会简单得多,它只是开箱即用:

uses Variants;

newDateTime := VarToDateTime('23/02/2011 12:34:56');
Run Code Online (Sandbox Code Playgroud)