Link to home
Start Free TrialLog in
Avatar of LeTay
LeTay

asked on

Convert a string into a TDateTime

I know that the StrToDateTime() function uses the locale settings to do the conversion of a string into a TDateTime
In my case, the string contains the date in this format : yyyy-mm-dd
So how can I convert it into TDateTime without locale settings interferences ?
Thanks
Avatar of SteveBay
SteveBay
Flag of United States of America image

The function you need is FormatDateTime
ex:
DateString := FormatDateTIme('mm/dd/yyyyy', Now );
Avatar of Mike McCracken
Mike McCracken

Try it this way


var
  MySettings: TFormatSettings;
  s: string;
  d: TDateTime;
begin
  GetLocaleFormatSettings(GetUserDefaultLCID, MySettings);
  MySettings.DateSeparator := '-';
  MySettings.TimeSeparator := ':';
  MySettings.ShortDateFormat := 'yyyy-mm-dd';
  MySettings.ShortTimeFormat := 'hh:nn:ss';

  s := DateTimeToStr(Now, MySettings);
  ShowMessage(s);
  d := StrToDateTime(s, MySettings);
  ShowMessage(DateTimeToStr(d, MySettings));
end;

Adapted from
http://www.distribucon.com/2006/01/10/DelphiStrToDateTimeWithFormatSettings.aspx

mlmcc
ASKER CERTIFIED SOLUTION
Avatar of Sinisa Vuk
Sinisa Vuk
Flag of Croatia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
There's an overload version of StrToDateTime() in SysUtils that let you pass your FormatSettings
In example
procedure TForm1.Button1Click(Sender: TObject);
var
  F: TFormatSettings;
  DT: TDateTime;
begin
  F.DateSeparator := '-';
  F.ShortDateFormat := 'yyyy-mm-dd';
  DT := StrToDateTime('2016-10-19', F);
  ShowMessage(DateTostr(DT));
end;

Open in new window

Avatar of LeTay

ASKER

Simple is beautiful !