0

In my big application I try to read another dateformat than my locale settings. But that failed with exception. So I made a simple demo to reproduce.

Could be that I made a simple error. My local settings in Windows XP is Finnish date format that is 'd.m.yyyy'. I want to read Swedish format that is 'yyyy-mm-dd'. Please help!

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.
4

1 回答 1

3

好的,得到了​​答案。我忘记了日期分隔符。所以为了避免在演示中出现异常,我添加了一行。然后必须使它更具活力...

function TForm5.GetCustomDateFormatSettings(aDateFormat: String): TFormatSettings;
begin
  GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, Result);
  Result.ShortDateFormat := aDateFormat;
  Result.DateSeparator := '-';
end;
于 2013-04-12T11:01:00.433 回答