开发者

Avoiding Locale Conflicts when storing TDateTime's in Floats?

I got the TDateTime thing fixed by using Floating vars 开发者_Go百科to store them in a file. However, now I face a new problem: Invalid Floating Point - Most likely because of the Comma Separator.

How can I set the default separator in my program? Or is there any other way around?


You can use a TFormatSettings record to specify the decimal separator when you call StrToFloat and FloatToStr. You have to decide what to use and stick to that. Here is sample code with a .

var
    d: TDateTime;
    s: string;
    fs: TFormatSettings;
begin
    d := Now();
    fs.DecimalSeparator := '.';
    s := FloatToStr(d, fs);
end;

Another option would be to use the XML standard date time format. Delphi has some functions in XSBuiltIns to do the conversion from TDateTime to string and back. You will have a time zone offset in the value so if you move your persisted TDateTime from one time zone to another you may have some unwanted behavior. It depends on the usage of the value.

var
    d: TDateTime;
    s: string;
begin
    d := Now();
    s := DateTimeToXMLTime(d);
    d := XMLTimeToDateTime(s);
end;


As Mikael suggested, there are a many ways to do this. To re-cap you wish to store a TDateTime to a file in textual format and be able to restore this value successfully irrespective of the locale on which the restoration happens.

Option 1

When storing, call FloatToStr, say, but force a '.' for the decimal separator through the TFormatSettings parameter. On restore, use StrToFloat with the same TFormatSettings.

Option 2

Encode the 8 byte TDateTime value using base 64. This has the downside that it renders the value unreadable.

Option 3

Similar to option 1, but encode the TDateTime by calling DateTimeToStr and explicitly passing a TFormatSettings that does not rely on anything in the locale – so do not rely on the locale's date or time separators, instead force your own. To reverse call StrToDateTime with an identical TFormatSettings record.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜