5

I am new in Delphi programming. While going through the Data Types in Delphi I found TDateTime.

While using it in my test application I come to know that the TDateTime Object provide me a Float\Double value.

I am little curious about TDateTime How it calculate the Date Time to Double value.

Below is the example code which I had used:

var
  LDateTime: TDateTime;
  LFloat: Double;
begin
   LDateTime := now;// current DateTime
   LFloat:= LDateTime; // provide me a float value   
end;

Is it using any formula to calculate Date and Time Value from Windows?

Can anyone suggest/provide me for some more information about working of TDateTime?

Thanks in advance.

A B
  • 1,461
  • 2
  • 19
  • 54
  • 2
    Are you tried reading the [documentation](http://docwiki.embarcadero.com/Libraries/XE5/en/System.TDateTime)? – RRUZ Jan 28 '15 at 05:35
  • Just for the record, `TDateTime` is not an object; it is a typedef of `type double`. From *System.pas*: `type TDateTime = type Double;`. There's no need to use `LFloat` to do any sort of conversion; you can directly use a `TDateTime` as a floating point value, as in `MyDate := Now + 10;` (add 10 days). – Ken White Jan 28 '15 at 13:52

2 Answers2

14

The float represents the number of days since 30.12.1899. So float value = 1 would be 31.12.1899, 2 = 01.01.1900 and so on. The time is saved as a fraction of the day. 0.25 = 06:00, 0.5 = 12:00, 0.75 = 18.00 ...

So the 31.12.1899 12:00 would be equal to 1.5.

This makes TDateTime really easy to work with. To get the difference in days just substract two DateTimes.

02.01.2015 - 01.01.2015 = 1

Simple as it can be. To get the difference in hours just multiply by 24.

Also have a look at the functions in Unit DateUtils. They come in handy at times.

Markus Müller
  • 2,611
  • 1
  • 17
  • 25
  • Also, the formula itself can be found under `EncodeDate` in unit SysUtils – Stijn Sanders Jan 28 '15 at 06:17
  • 3
    Note that using TDateTime as a Double is an implementation detail and should be avoided. There are lots of routines that handles TDateTime values is SysUtils and DateUtils. See [Date and Time Support](http://docwiki.embarcadero.com/RADStudio/en/Date_and_Time_Support). – LU RD Jan 28 '15 at 07:30
1

You are looking for

function DateTimeToUnix(const AValue: TDateTime): Int64;

and

function UnixToDateTime(const AValue: Int64): TDateTime;

functions from DateUtils.pas

TDateTime value can be formatted by FormatDateTime function

//uses sysutils

var    
  k:double;    
  t:tdatetime    
begin    
  t:=UnixToDateTime(1483909200);    
  showmessage(datetostr(t));    
  t:=strtodate('08.01.2017');    
  k:=DateTimeToUnix(t);    
  showmessage(k.ToString);    
end;
LU RD
  • 34,438
  • 5
  • 88
  • 296