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
969 views
in Technique[技术] by (71.8m points)

delphi - Converting a string to TDateTime based on an arbitrary format

Is there any way in Delphi 5 to convert a string to a TDateTime where you can specify the actual format to use?

I'm working on a jobprocessor, which accepts tasks from various workstations. The tasks have a range of parameters, some of which are dates, but (unfortunately, and out of my control) they're passed as strings. Since the jobs can come from different workstations, the actual datetime format used to format the dates as a string might (and, of course, actual do) differ.

Googling around, the only quick solutions I found was to sneakily change the ShortDateFormat variable, and restore it to its original value afterwards. Since ShortDateFormat is a global variable, and I'm working in a threaded environment the only way this would work is by synchronizing every access to it, which is completely unacceptable (and undoable).

I could copy the library code from the SysUtils unit into my own methods, and tweak them to work with a specified format instead of the global variables, but I'm just wondering if there's something more adequate out there that I missed.

Kind regards, and thanks in advance,

Willem

UPDATE

To put it more succinctly:

I need something like StrToDate (or StrToDateTime), with the added option of specifying the exact format it should use to convert the string to a TDateTime.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use VarToDateTime instead. It supports many more date formats in the string and converts them automatically.

var
  DateVal: TDateTime;
begin
  DateVal := VarToDateTime('23 Sep 2010');
  ShowMessage(DateToStr(DateVal));
end;

I see you're using Delphi 5. Some versions of Delphi will need to add Variants to the uses clause; most later versions add it for you. I don't remember which category Delphi 5 fell into.


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

...