【问题标题】:Is there a Delphi RTL function that can convert the ISO 8601 basic date format to a TDate?是否有可以将 ISO 8601 基本日期格式转换为 TDate 的 Delphi RTL 函数?
【发布时间】:2014-07-29 07:27:50
【问题描述】:

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。

【问题讨论】:

  • 不确定RTL 是否可以帮助您,但XSBuiltIn 可以。它可以使用TXSDatetime 轻松转换。在他的blog 上检查@JeroenWiertPluimers 转换单元。
  • TXSDate.XSToNative 针对这种格式抛出 EConvertError 'Invalid argument to date encode'。
  • Indy 的IdDateTimeStamp.pas 似乎也不支持基本日期格式。但@RemyLebeau 或许可以验证这一点。
  • 你也应该看看link
  • @dummzeuch,刚刚测试过,你是对的。问题在于它试图提取年、月和日。如果没有某种分隔符,TXSDate 似乎无法这样做。

标签: delphi iso8601 delphi-xe6


【解决方案1】:

您可以像以前一样使用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;

【讨论】:

  • 同理,你可以先把整个字符串转成int,然后用div和mod拉出年月日。
  • 是的,我可以。因为我已经知道它是所描述的格式。太简单了,我猜。不过,我想知道为什么 Delphi 显然无法处理它。
  • @dummzeuch 恕我直言 Delphi 的 dateutils 单元是整个 Delphi 标准库中最差的单元。它似乎甚至早于面向对象。实际上,Turbo Pascal 具有将日期转换为记录的功能,遗憾的是,这意味着 TP 为您提供了一种比 Delphi 更结构化的日期处理方式。 :-( 为什么 Delphi 无法处理它的答案是,自从 Delphi 1 以来,没有人重新访问 dateutils 并更新了它的最小功能。哎呀,我们的日期时间甚至没有天生的时区意识。:-( 解析 ISO 8601 没有问题其他语言。
  • @alcalde 这不公平。这些年来,dateutils 已经有了很多改进。但它远非完美,这是真的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
相关资源
最近更新 更多