在我的大应用程序中,我尝试读取另一个dateformat而不是我的语言环境设置。但那失败了,例外。所以我做了一个简单的演示来重现。
可能是我犯了一个简单的错误。我在Windows XP中的本地设置是芬兰语日期格式'd.m.yyyy'。我想阅读'yyyy-mm-dd'的瑞典格式。请帮忙!
unit Unit5;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
const
cnFormat = 'yyyy-mm-dd'; // Swedish dateformat
cnFIFormat = 'd.m.yyyy'; // Finnish dateformat
type
TForm5 = class(TForm)
procedure FormCreate(Sender: TObject);
private
fSetting: TFormatSettings;
function GetCustomDateFormatSettings(aDateFormat: String = cnFormat): TFormatSettings;
function GetSafeDate(aDate: String): TDate;
end;
var
Form5: TForm5;
implementation
{$R *.dfm}
procedure TForm5.FormCreate(Sender: TObject);
var
vDate: TDate;
begin
fSetting := GetCustomDateFormatSettings;
vDate := GetSafeDate('2010-01-04');
end;
function TForm5.GetCustomDateFormatSettings(aDateFormat: String): TFormatSettings;
begin
GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, Result);
Result.ShortDateFormat := aDateFormat;
end;
function TForm5.GetSafeDate(aDate: String): TDate;
begin
try
Result := StrToDate(aDate, fSetting); // <- Exception here
except
on E: EConvertError do
begin
// logic to recover from exception
end;
end;
end;
end.
答案 0 :(得分:3)
好的,得到了答案。我忘记了DateSeparator。所以为了避免在演示中出现异常,我添加了一行。必须让那更具活力......
function TForm5.GetCustomDateFormatSettings(aDateFormat: String): TFormatSettings;
begin
GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, Result);
Result.ShortDateFormat := aDateFormat;
Result.DateSeparator := '-';
end;