Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

delphi

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?

like image 463
steve0 Avatar asked Jul 25 '10 19:07

steve0


2 Answers

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);
like image 199
RRUZ Avatar answered Sep 28 '22 03:09

RRUZ


Using VarToDateTime might be a lot simpler and it just works out of the box:

uses Variants;

newDateTime := VarToDateTime('23/02/2011 12:34:56');
like image 25
Kromster Avatar answered Sep 28 '22 05:09

Kromster