4

ISO 8601 描述了一种不使用破折号的所谓基本日期格式:

20140507 是更易读的 2014-05-07 的有效表示。

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

我试过了

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。

4

1 回答 1

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;
于 2014-06-08T17:35:34.703 回答