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

Categories

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

delphi - how I can convert str to datetime?

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

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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...