[英]How to convert string to date in delphi
当我将string
类型转换为TDateTime
我收到一个错误。 我正在使用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;
使用VarToDateTime
从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;
设置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;
这些似乎是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
尝试使用StrToDateTime
函数将string
DateTime转换为TDateTime
值。 请注意,传递的日期时间格式应为当前系统日期/时间格式,否则将引发异常。 一个例子: StrToDateTime('2018-07-11 12:34:56');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.