1. Home
  2. Computing & Technology
  3. Delphi Programming

How to store a TDateTime in the Registry

By , About.com Guide

Converting it to a string and then back is not always satisfactory as people can change their date and time formats and we do not want to impose any restrictions on the software. TDateTime is a float, so we can store it as a binary value.

~~~~~~~~~~~~~~~~~~~~~~~~~
program DateRegistry;

uses
   Windows,
   Dialogs,
   Registry,
   SysUtils;


{$R *.RES}

procedure SaveDate
  (const sKey: string;
   const sField: string;
   aDate: TDateTime) ;
begin
   with TRegistry.Create do
   begin
     RootKey := HKEY_CURRENT_USER;
     if OpenKey(sKey, True) then
     begin
       WriteBinaryData(sField, aDate, SizeOf(aDate)) ;
       CloseKey;
     end;
     Free;
   end;
end;

function ReadDate
   (const sKey: string;
    const sField: string) : TDateTime;
begin
   // default: return 0
   Result := 0;

   with TRegistry.Create do
   begin
     RootKey := HKEY_CURRENT_USER;
     if OpenKey(sKey, False) then
     begin
       try
         ReadBinaryData(sField, Result, SizeOf(Result)) ;
       except
       end;
       CloseKey;
     end;
     Free;
   end;
end;

var
   dDate: TDateTime;

begin
   // save the date
   SaveDate('\DateTimeDemo', 'LastDate', Now) ;

   // retrieve it
   dDate := ReadDate('\DateTimeDemo', 'LastDate') ;

   // show it
   ShowMessage(DateTimeToStr(dDate)) ;
end.
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» How to Convert a String of Integers into an Array of Byte
« Adding an icon to the standard Windows About dialog

Explore Delphi Programming
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2002 Delphi Tips
  7. How to store a TDateTime in the Registry

©2009 About.com, a part of The New York Times Company.

All rights reserved.