When I convert string
type to TDateTime
I get an error. I'm using VarToDateTime
function. My date as string is 2018-07-11T13:45:14.363
.
var
s: string;
v: Variant;
dt: TDateTime;
begin
s := '2018-07-11T13:45:14.363';
v := s;
dt := VarToDateTime(v);
end;
The success of a conversion from string
to TDateTime
using VarToDateTime
depends on locale settings in the users system. The conversion fails if those settings do not match the string. This is the reason why the conversion fails on my system, as also on yours.
The primary option, if you are working with Delphi XE6 or later, is to use function ISO8601ToDate()
as suggested by Marc Guillot in another answer
If you are workin with Delphi 2010 or later you can use the solution presented here.
Earlier versions than Delphi 2010 choke on the "T" in the input string, and may succeed if the "T" is removed or replaced with a space.
Use a conversion function which accepts a TFormatSetting
that can be adjusted according to the string to convert. Such a function is the following overload of StrToDateTime()
(See Embarcadero document)
function StrToDateTime(const S: string; const AFormatSettings: TFormatSettings): TDateTime;
Setting AFormatSettings
to match the string to convert, ensures that the conversion succeeds:
procedure TForm3.Button1Click(Sender: TObject);
var
fs: TFormatSettings;
s: string;
dt: TDateTime;
begin
fs := TFormatSettings.Create;
fs.DateSeparator := '-';
fs.ShortDateFormat := 'yyyy-MM-dd';
fs.TimeSeparator := ':';
fs.ShortTimeFormat := 'hh:mm';
fs.LongTimeFormat := 'hh:mm:ss';
s := '2018-07-11T13:45:14.363';
dt := StrToDateTime(s, fs);
end;
These seems to be ISO8601 datetime strings : https://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations
So on Delphi XE 6 and later you can use the corresponding conversion function : ISO8601ToDate
http://docwiki.embarcadero.com/Libraries/XE8/en/System.DateUtils.ISO8601ToDate
But if you are using an older version of Delphi then you can use the XMLTimeToDateTime function on the XSBuiltIns unit to do that conversion (available since Delphi 6).
http://docwiki.embarcadero.com/Libraries/Tokyo/en/Soap.XSBuiltIns.XMLTimeToDateTime
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With