Delphi无效ReadDateTime [英] Delphi inifiles ReadDateTime

查看:82
本文介绍了Delphi无效ReadDateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下内容的本质:

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;

ini文件中的条目顺利通过。在文件中写入到04-Dec-63 17:28:14。从ini文件中读取也无效,消息变为 04-Dec-63 17:28:14无效的日期和时间。

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

Windows 7 Enterprise х32, Embarcadero Delphi XE Portable

推荐答案

您已将日期/时间以文本形式写入文件。并使用创建该文件的用户的语言环境设置对其进行格式化。您注定无法可靠地读取此文件,因为不同的用户具有不同的区域设置。您需要为日期不依赖于语言环境使用可靠的格式。

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. 存储为浮点使用 TDateTime 的基础表示形式。

  2. 使用预定格式存储为文本。

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

对于选项1,您将需要确保使用预定的十进制分隔符,以避免出现与现在完全相同的问题!这意味着您需要在 TDateTime string 之间执行自己的转换,因为 WriteFloat ReadFloat 方法使用与区域设置相关的全局格式设置。在 SysUtils 中有 FloatToStr StrToFloat 的重载可以接受

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.

对于选项2,RTL包含用于使用指定格式执行日期/时间转换的各种功能。在 SysUtils 中有 DateTimeToStr StrToDateTime 的重载可以接受格式设置参数。

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.

如果您希望文件易于被人阅读或编辑,则首选选项2。

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

这篇关于Delphi无效ReadDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆