Checking two TDateTime variables

こ雲淡風輕ζ 提交于 2019-12-01 01:07:46
Ken White

The difference is 1 day, 22 hours.

TDateTime in Delphi and C++ Builder is a double, where the whole portion (the part to the left of the decimal point) stores the number of days since a base date of December 30, 1899 (see note below), and the fractional portion (the part to the right of the decimal point) is the time.

The 1899 you're seeing after the subtraction is because you have less than a full day, and therefore the whole portion of the number is zero, and as I mentioned a date of zero is the base date in December, 1899. Since your date is 1 day later than that base date (when represented as a TDateTime, the date is interpreted as December 31, 1899.

The time portion for 22 hours is approximately 0.9167 (actually, 0.916666666666667), which represents 22/24ths of a day.

Delphi's runtime library contains a unit called DateUtils, which IIRC is available to C++ Builder as well (there's a header file for it), which contains functions which may help you, like DaysBetween that you may find useful. There are C++ examples of it's use available here.

As far as equality (one date being after the other), you can use the standard >, <, >=, <=, !=, and == operators. I've demonstrated this below as well.

Here's a quick example (in Delphi, as I don't have C++ Builder installed on this machine) that might explain:

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, DateUtils;

var
  StartDate, EndDate, Diff: TDateTime;
begin
  try
    { TODO -oUser -cConsole Main : Insert code here }
    // Base date, formatted in US date format
    WriteLn('BaseDate: ', FormatDateTime('mm/dd/yyyy hh:nn:ss', 0));

    StartDate := EncodeDateTime(2012, 9, 11, 14, 0, 0, 0);
    EndDate := EncodeDateTime(2012, 9, 12, 16, 0, 0, 0);
    Diff := EndDate - StartDate;

    WriteLn('Diff as String: ', DateToStr(Diff));
    WriteLn('Diff as Double: ', Diff);
    WriteLn('DaysBetween: ', DaysBetween(EndDate, StartDate));

    // Equality
    WriteLn('EndDate after StartDate`, EndDate > StartDate);
    RegEx.Free;
    ReadLn;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

This produces this output:

BaseDate: 12/30/1899 00:00:00
Diff as String: 12/31/1899
Diff as Double:  1.08333333332848E+0000
DaysBetween: 1
EndDate after StartDate: TRUE

NOTE: The base date was established by Microsoft for COM, and for compatibility reasons Delphi/C++ Builder adopted it.

You can use your normal -, +, <, >,== and = with TDateTime.

So to see if one date is ahead of another, you can, for example, subtract them and see if the result is greater or lesser than zero.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!