Board index » delphi » Converting a date/time string

Converting a date/time string

I'm having problems converting a date/time string using StrToDateTime.  The
format of the string is 'MMDDYYYYHHMMSS'.

I've set ShortDateFormat to 'mmddyyyy' and ShortTimeFormat to 'hhmmss'.
However, since there are no separators, StrToDateTime fails (specifically,
ScanDate and ScanTime fail).
This occurs while importing data from a comma-delimited file into a
TDataSet.  The data is being converted via TField.AsString, which calls
StrToDateTime for TDateTimeFields.  The importing is done inside a component
that I wrote.  Within the component, I can't reformat this field into a
better format because it is a general purpose component.

I thought I could solve the problem by setting ShortDateFormat and
ShortTimeFormat before using the component.  This has worked with other
formats.  But the problem with this format is that lack of date separators
and time separators.

Anyone know a way to get StrToDateTime to handle this format (without
rewriting it, of course)?

Thanks.

 

Re:Converting a date/time string


Jon -

As you figured, the problem is that StrToDateTime is not
enforcing the limit on field length. That allows you to enter
something like 1:10 instead of 01:10 and 1/1/1 instead of
01/01/2001. So the only way to "fix" that is to rewrite
StrToDateTime. But be warned that you may break a lot of other
code if you enforce the limit. Be careful.

Good luck.

Kurt

Re:Converting a date/time string


Quote
In article <39f0696a$1_2@dnews>, Jon Robertson wrote:
> I'm having problems converting a date/time string using StrToDateTime.  The
> format of the string is 'MMDDYYYYHHMMSS'.

Don't use it. Write yourself a simple helper function instead. As a starter,
without any error checking:

  function ConvDate(const d: string): TDateTime;
  var mm,dd,yyyy,hour,mins,secs: word;
  begin
    mm := StrToInt(Copy(d,1,2));
    dd:= StrToInt(Copy(d,3,2));
    yyyy:= StrToInt(Copy(d,5,4));
    hour:= StrToInt(Copy(d,9,2));
    mins:= StrToInt(Copy(d,11,2));
    secs:= StrToInt(Copy(d,13,2));
    Result := EncodeDate(yyyy,mm,dd)+EncodeTime(hour,mins,secs,0);
  end
 (untested)

 Mike Orriss (TeamB & Developer Express)
 (Unless stated otherwise, my replies relate to Delphi 5)
 (No unsolicited e-mail replies please)

Other Threads