简体   繁体   中英

How to convert string to date in delphi

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

Try the function StrToDateTime which converts a string DateTime into a TDateTime value. Note that the datetime format passed should be the current system date/time format or else it will throw an exception. An example: StrToDateTime('2018-07-11 12:34:56');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM