Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

delphi - '23/02/2011 12:34:56' is not valid date and time

In my code I am facing a problem. Example code:

var 
    d1: tdatetime
begin
    d1 := strtodatetime('23/02/2011 12:34:56');
end; 

but it's giving the error:

'23/02/2011 12:34:56' is not valid date and time

What's wrong with what I am doing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

the StrToDateTime function uses the ShortDateFormat and DateSeparator to convert the date part and the LongTimeFormat and TimeSeparator to the time part. so you string must match with theses variables to convert the string to TDateTime. instead you can use the StrToDateTime with the TFormatSettings parameter, to parse you string.

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

check this sample

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...