当我将string类型转换为TDateTimeI时出错.我正在使用VarToDateTime功能.我作为字符串的日期是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;
Run Code Online (Sandbox Code Playgroud)
Tom*_*erg 12
转换string成TDateTime使用的成功VarToDateTime取决于用户系统中的区域设置.如果这些设置与字符串不匹配,则转换失败.这就是我的系统转换失败的原因,也是你的系统转换失败的原因.
如果您正在使用Delphi XE6或更高版本,主要选项是使用Marc Guillot 在另一个答案中ISO8601ToDate()建议的功能
如果您正在使用Delphi 2010或更高版本,则可以使用此处提供的解决方案.
早于Delphi 2010的版本会阻塞输入字符串中的"T",如果删除"T"或用空格替换,则可能会成功.
使用转换函数接受TFormatSetting可以根据要转换的字符串进行调整的函数.这样的功能是以下超载StrToDateTime()(参见Embarcadero文件)
function StrToDateTime(const S: string; const AFormatSettings: TFormatSettings): TDateTime;
Run Code Online (Sandbox Code Playgroud)
设置AFormatSettings为匹配要转换的字符串,确保转换成功:
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;
Run Code Online (Sandbox Code Playgroud)
这些似乎是ISO8601日期时间字符串:https://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations
因此,在Delphi XE 6及更高版本中,您可以使用相应的转换函数:ISO8601ToDate
http://docwiki.embarcadero.com/Libraries/XE8/en/System.DateUtils.ISO8601ToDate
但是如果您使用的是旧版本的Delphi,则可以使用XSBuiltIns单元上的XMLTimeToDateTime函数进行该转换(自Delphi 6起可用).
http://docwiki.embarcadero.com/Libraries/Tokyo/en/Soap.XSBuiltIns.XMLTimeToDateTime