是否有可以将ISO 8601基本日期格式转换为TDate的Delphi RTL功能?

时间:2014-06-08 17:18:40

标签: delphi iso8601 delphi-xe6

ISO 8601描述了一种不使用短划线的所谓基本日期格式:

20140507是2014-05-07更具可读性的有效表示。

是否有Delphi RTL函数可以解释该基本格式并将其转换为TDateTime值?

我试过

function TryIso2Date(const _s: string; out _Date: TDateTime): Boolean;
var
  Settings: TFormatSettings;
begin
  Settings := GetUserDefaultLocaleSettings;
  Settings.DateSeparator := #0;
  Settings.ShortDateFormat := 'yyyymmdd';
  Result := TryStrToDate(_s, Date, Settings);
end;

TryIso2Date('20140507', dt);

但它没有用,因为在字符串中找不到DateSeparator。

我到目前为止唯一提出的解决方案(除了自己编写解析代码)是在调用TryStrToDate之前添加缺少的破折号:

function TryIso2Date(const _s: string; out _Date: TDateTime): Boolean;
var
  Settings: TFormatSettings;
  s: string;
begin
  Settings := GetUserDefaultLocaleSettings;
  Settings.DateSeparator := #0;
  Settings.ShortDateFormat := 'yyyy-mm-dd';
  s := Copy(_s,1,4) + '-' + Copy(_s, 5,2) + '-' + Copy(_s, 7);
  Result := TryStrToDate(_s, Date, Settings);
end;

TryIso2Date('20140507', dt);

这有效,但感觉相当笨拙。

这是Delphi XE6,因此它应该有最新的RTL。

1 个答案:

答案 0 :(得分:2)

您可以使用Copy来提取值。然后你只需要编码日期:

function TryIso8601BasicToDate(const Str: string; out Date: TDateTime): Boolean;
var
  Year, Month, Day: Integer;
begin
  Assert(Length(Str)=8);
  Result := TryStrToInt(Copy(Str, 1, 4), Year);
  if not Result then
    exit;
  Result := TryStrToInt(Copy(Str, 5, 2), Month);
  if not Result then
    exit;
  Result := TryStrToInt(Copy(Str, 7, 2), Day);
  if not Result then
    exit;
  Result := TryEncodeDate(Year, Month, Day, Date);
end;