Delphi : Convert a String to TDateTime

In Delphi concerting string to TDateTime is always an issue for me: Here is the code to help someone.


var
   myformat : TFormatSettings;
   theDate : TDateTime;
begin

   GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, myformat );
   myformat.DateSeparator := '/';
   myformat.TimeSeparator := ':';
   myformat.ShortDateFormat := 'dd/mm/YYYY hh:nn';
 theDate  := StrToDateTime( '01/01/2017',myformat);
end;

Hope this helps someone.

The inverse is easier:


MyStr := FormatDateTime('dd/mm/yyyy HH:nn:ss',theDate));

If you have the Project Jedi Components JVCL Delphi Jedi you can use the

JvJCLUtils.StrToDateFmt ( 'yyyy/mm/dd', '2017/01/01' );

from the JvJCLUtils.pas file.

Leave a Reply

Your email address will not be published. Required fields are marked *