Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

delphi - Conversion with StrToDateTime and TFormatSettings does not work

This code should work in Delphi XE2, but it gives "not a valid date and time" error in StrtoDateTime conversion:

procedure TForm2.Button1Click(Sender: TObject);
var
  s: string;
  d: TDateTime;
  FmtStngs: TFormatSettings;
begin
    GetLocaleFormatSettings(GetThreadLocale, FmtStngs);
    FmtStngs.DateSeparator := #32;
    FmtStngs.ShortDateFormat := 'dd mmm yyyy';
    FmtStngs.TimeSeparator := ':';
    FmtStngs.LongTimeFormat := 'hh:nn';

    s := FormatDateTime('', Now, FmtStngs);
    d := StrToDateTime(s, FmtStngs);
end;

Any hints?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to convert some special DateTime-Formats you should better use VarToDateTime instead of StrToDateTime. Just have a look at the implementation of both and you will recognize, that StrToDateTime is somehow ... and VarToDateTime will ask the OS if it can't determine by itself.

This works with Delphi XE3 (but should also work with earlier versions):

procedure TForm2.Button1Click( Sender: TObject );
var
  s: string;
  d: TDateTime;
  FmtStngs: TFormatSettings;
begin
    GetLocaleFormatSettings( GetThreadLocale, FmtStngs );
    FmtStngs.DateSeparator := #32;
    FmtStngs.ShortDateFormat := 'dd mmm yyyy';
    FmtStngs.TimeSeparator := ':';
    FmtStngs.LongTimeFormat := 'hh:nn';

    s := FormatDateTime( '', Now, FmtStngs );
    d := VarToDateTime( s );
end;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...