简体   繁体   中英

Delphi equivalent of .net's DateTime.ToString(“s”) (DateTime Sortable)

Is there an equivalent in Delphi? I've looked over the documentation and can't find anything that would give me the output I want.

kdunlapmo, the DateTime.ToString(“s”) function return an Sortable date/time pattern; conforms to ISO 8601. this pattern is declarated as "yyyy-MM-ddTHH:mm:ss" . regardless of the culture, the date must always be returned in the same format. you can use the FormatDateTime function in delphi to format an TDateTime value into a string.

you can use something like this

FormatDateTime('yyyy-mm-dd"T"hh:mm:ss', Now);

but you must be careful because the - character is Substituted by the DateSeparator value and the : character is Substituted by the TimeSeparator value, both variables are depending on the Windows locale configuration. so to avoid problems getting distinct results when the culture changes you must use explicity the - and the : characters in your format string.

FormatDateTime('yyyy"-"mm"-"dd"T"hh":"mm":"ss', Now)

see this sample code

program ProjectTestFormat;

{$APPTYPE CONSOLE}

uses
  SysUtils;

begin
  try        
    DateSeparator:='/';
    TimeSeparator:='.';
    //this string is affected by the windows locale configuration
    Writeln(FormatDateTime('yyyy-mm-dd"T"hh:mm:ss', Now));
    //this string is not affected
    Writeln(FormatDateTime('yyyy"-"mm"-"dd"T"hh":"mm":"ss', Now));
    Readln;
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end.

Additionally you can write a function to convert an TDatetime value to the sortable format, see this sample

function GetSortableDatetimeFormat(Value:TDateTime):string;
begin
  Result:=FormatDateTime('yyyy"-"mm"-"dd"T"hh":"mm":"ss', Value);
end;

Little bugfix - right is:

Result:=FormatDateTime('yyyy"-"mm"-"dd"T"hh":"nn":"ss', Value);

(minutes is "nn", not "mm")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM