Question

The essence in the following:

procedure TForm1.Button1Click(Sender: TObject);
var
  cfile: TInifile;
  Date1: TDateTime;
begin
  Date1 := IncYear(Now, -50);
  cfile := TInifile.Create(ExtractFilePath(Application.ExeName) + 'Settings.ini');
  try
    cfile.WriteDateTime('Main', 'DateTime', Date1);
    ShowMessage('Recorded in the ini file ' + DateTimeToStr(Date1));
    Date1 := cfile.ReadDateTime('Main', 'DateTime', Now);
    ShowMessage('Read from ini file ' + DateTimeToStr(Date1));
  finally
    cfile.Free;
  end;
end;

Entry in the ini file passes without problems. In the file is written to 04-Dec-63 17:28:14. Read also from ini file does not work, the message falls "04-Dec-63 17:28:14 is not a valid date and time".

Windows 7 Enterprise х32, Embarcadero Delphi XE Portable

Was it helpful?

Solution

You've written the date/time to the file as text. And formatted it using the locale settings of the user who created that file. You are doomed to fail to read this file reliably since different users have different locale settings. You need to use a robust format for the date that does not depend on locale.

The two options that seem most natural:

  1. Store as a floating point value, using the underlying representation of TDateTime.
  2. Store as text using a pre-determined format.

For option 1 you'll need to make sure you use a pre-determined decimal separator to avoid the exact same problem you have now! That means you'll need to perform your own conversion between TDateTime and string because the WriteFloat and ReadFloat methods use the global format settings which are locale dependent. There are overloads of FloatToStr and StrToFloat in SysUtils that accept a format settings parameter.

For option 2, the RTL contains various functions to perform date/time conversions using specified formats. There are overloads of DateTimeToStr and StrToDateTime in SysUtils that accept a format settings parameter.

Option 2 is to be preferred if you wish the file to be easily read or edited by a human.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top