how I can convert str to datetime?

后端 未结 1 1741
悲&欢浪女
悲&欢浪女 2020-12-12 00:39

How I can convert \"02 August 2012 18:53\" to DateTime?

when I use StrToDate for convert it occur error \'Invalid Date format\'

1条回答
  •  时光说笑
    2020-12-12 00:56

    You can use VarToDateTime (found in the Variants unit), which supports various time formats Delphi's RTL doesn't. (It's based on COM's date support routines like the ones used in various Microsoft products.) I tested with your supplied date, and it indeed converts it to a TDateTime properly. Tested on both Delphi 2007 and XE2.

    program Project2;
    
    {$APPTYPE CONSOLE}
    
    {$R *.res}
    
    uses
      SysUtils, Variants;
    
    
    var
      DT: TDateTime;
      TestDate: String;
    
    begin
      TestDate := '02 August 2012 18:53';
    
      try
        DT := VarToDateTime(TestDate);
        { TODO -oUser -cConsole Main : Insert code here }
      except
        on E:Exception do
          Writeln(E.Classname, ': ', E.Message);
      end;
      Writeln(FormatDateTime('mm/dd/yyyy hh:nn', DT));
      Readln;
    end.
    

    More info in the current documentation , including another sample of use (link at the bottom of that page).


    Note the function in Variants unit use the default user locale. If it is not 'US' the conversion from the above string might fail. In that case you would better call VarDateFromStr directly from activex unit specifying the US locale:

    uses
      sysutils, activex, comobj;
    
    var
      TestDate: String;
      DT: TDateTime;
    begin
      try
        TestDate := '02 August 2012 18:53';
        OleCheck(VarDateFromStr(WideString(TestDate), $0409, 0, Double(DT)));
        Writeln(FormatDateTime('mm/dd/yyyy hh:nn', DT));
        Readln;
      except
        on E:Exception do
          Writeln(E.Classname, ': ', E.Message);
      end;
    end.
    

    0 讨论(0)
提交回复
热议问题