Welcome to OStack Knowledge Sharing 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 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...