DelphiFAQ Home Search:

Best way to store a TDateTime in the registry

 

commentsThis article has not been rated yet. After reading, feel free to leave comments and rate it.

Question:

What is the best/most commonly used format for storing TDateTime in the reguistry ? 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.


Answer:

TDateTime is a float, so you can store it as a binary value. See the sample code below.
Download file DateRegistry.dpr.

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('\Software\preview\Demo', 'LastDate', Now);

  // retrieve it
  dDate := ReadDate('\Software\preview\Demo', 'LastDate');

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

Comments:

2006-11-27, 03:06:09
anonymous from China  
commonly

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: