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.