delphi 在DateToISO8601上丢失毫秒

mwngjboj  于 2023-01-05  发布在  其他
关注(0)|答案(3)|浏览(184)

很多API都希望ISO8601中没有毫秒,如下所示:
仅获取此时间戳之后下达的订单。格式应为YYYY-MM-ddTHH:mm:ssZ
我想主要的"问题"是秒后面的点(秒和毫秒之间),人们必须对点进行url编码(http GET),对吗?

SDateFormat: string = 'yyyy''-''mm''-''dd''T''hh'':''nn'':''ss''.''zzz''Z'''; { Do not localize }

我不能失去毫秒。

DateToISO8601(TTimeZone.Local.ToUniversalTime(RecodeMilliSecond(now, 0), false), true)

这是我目前的做法:

var
  utc: TDateTime;
...
  utc := TTimeZone.Local.ToUniversalTime(now);
  utc := RecodeMilliSecond(utc, 0);
  ... Format('/orders?storefront=de&ts_created_from_iso=%sT%sZ', [FormatDateTime('yyyy-mm-dd', utc), FormatDateTime('hh:nn:ss', utc)])

还有别的主意吗?

ws51t4hk

ws51t4hk1#

如果我没理解错你的问题,你想知道如何让DateToISO8601()不输出毫秒,对吗?答案是,你不能。但是,在使用System.Delete()TStringHelper.Remove()之后,很容易去掉毫秒,因为你知道结果字符串中毫秒的确切偏移量和长度。

var
  utc: TDateTime;
  iso: string;
... 
  utc := TTimeZone.Local.ToUniversalTime(Now);
  iso := DateToISO8601(utc, true);
  Delete(iso, 20, 4);
  ... '/orders?storefront=de&ts_created_from_iso=' + iso;

否则,您可以继续使用手动方法。但是,您不需要RecodeMilliseconds(),只需调用一次FormatDateTime()就足够了:

const
  cISOFormat: string = 'yyyy''-''mm''-''dd''T''hh'':''nn'':''ss''Z''';
var
  utc: TDateTime;
...
  utc := TTimeZone.Local.ToUniversalTime(Now);
  ... '/orders?storefront=de&ts_created_from_iso=' + FormatDateTime(cISOFormat, utc);
nxowjjhe

nxowjjhe2#

这是我们使用的例行程序:

function DateTimeToXML(dtInput: TDateTime): String;
  var
    fmt: TFormatSettings;
  begin
    // If this will be used in a multithreaded environment then
    // you should use your own TFormatSettings to be thread safe
    fmt:=TFormatSettings.Create();      // initialize, it's on the stack so MUST NOT be freed
    DateTimeToString(Result, 'yyyy-mm-dd''T''hh:nn:ss''Z''',
                     TTimeZone.Local.ToUniversalTime(dtInput), fmt);
  end;
fzsnzjdm

fzsnzjdm3#

您可以从System.DateUtils复制函数DateToISO8601并将其更改为:

function [MyClassName].DateToISO8601(const ADate: TDateTime; AInputIsUTC: Boolean = true): string;
const
  SDateFormat: string = '%.4d-%.2d-%.2dT%.2d:%.2d:%.2dZ'; { Do not localize }
  SOffsetFormat: string = '%s%s%.02d:%.02d'; { Do not localize }
  Neg: array[Boolean] of string = ('+', '-'); { Do not localize }
var
  y, mo, d, h, mi, se, ms: Word;
  Bias: Integer;
  TimeZone: TTimeZone;
begin
  DecodeDate(ADate, y, mo, d);
  DecodeTime(ADate, h, mi, se, ms);
  Result := Format(SDateFormat, [y, mo, d, h, mi, se]);
  if not AInputIsUTC then
  begin
    TimeZone := TTimeZone.Local;
    Bias := Trunc(TimeZone.GetUTCOffset(ADate).Negate.TotalMinutes);
    if Bias <> 0 then
    begin
      // Remove the Z, in order to add the UTC_Offset to the string.
      SetLength(Result, Result.Length - 1);
      Result := Format(SOffsetFormat, [Result, Neg[Bias > 0], Abs(Bias) div 
MinsPerHour,
        Abs(Bias) mod MinsPerHour]);
    end
  end;
end;

相关问题