Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 712
Moore Avatar asked Nov 09 '12 12:11

Moore


2 Answers

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;
like image 162
Sir Rufo Avatar answered Sep 25 '22 23:09

Sir Rufo


You have two issues

  1. You can't use a WhiteSpace as DateSeparator, because the internal routines to parse the string uses this character to determine the date and time parts of the string.

  2. The StrToDateTime function does not work when the months part use the mmm string, this is reported in this QC 23301

like image 28
RRUZ Avatar answered Sep 25 '22 23:09

RRUZ