Recent

Author Topic: FormatDateTime exceptions  (Read 809 times)

RobA

  • New Member
  • *
  • Posts: 19
FormatDateTime exceptions
« on: September 03, 2024, 02:04:18 am »
Hi all,

I'm a bit puzzled by FormatDateTime and EConvertError. According to the docs:

"FormatDateTime formats the date and time encoded in DateTime according to the formatting given in FormatStr. The complete list of formatting characters can be found in formatchars."

and:

"On error (such as an invalid character in the formatting string), and EConvertError exception is raised."

Based on that, I assumed that if FormatStr contained characters not listed in formatchars, and not a literal, then it would raise an exception. Indeed,

Code: Pascal  [Select][+][-]
  1. try
  2.     writeln('Test: '+formatdatetime('a',Now));
  3.   except
  4.     on E:EConvertError do
  5.       writeln(E.Message);
  6.   end;

does exactly that. But
Code: Pascal  [Select][+][-]
  1. try
  2.     writeln('Test: '+formatdatetime('b',Now));
  3.   except
  4.     on E:EConvertError do
  5.       writeln(E.Message);
  6.   end;
does not. Instead, it prints an upper case B to the console (it's a basic console program). Why does this happen, given that neither a nor b are listed in FormatChars? I was hoping to accept arbitrary format strings as command line parameters, and just pass them directly to FormatDateTime on the assumption that I could catch any invalid character via EConvertError, but it looks like I can't do that. Do I have to parse the user-supplied format strings myself?

TIA,

Rob

Zvoni

  • Hero Member
  • *****
  • Posts: 3307
Re: FormatDateTime exceptions
« Reply #1 on: September 03, 2024, 10:44:55 am »
Because the "a" gets interpreted as an incomplete "12hours"-Formatstring, while the "b" gets interpreted as an literal

FormatDateTime calls DateTimeToString.
Look in dati.inc
C:\lazarus\fpc\3.2.2\source\rtl\objpas\sysutils\dati.inc
Beginning in Line 1014 (at least in my installation)
One System to rule them all, One Code to find them,
One IDE to bring them all, and to the Framework bind them,
in the Land of Redmond, where the Windows lie
---------------------------------------------------------------------
Code is like a joke: If you have to explain it, it's bad

RobA

  • New Member
  • *
  • Posts: 19
Re: FormatDateTime exceptions
« Reply #2 on: September 04, 2024, 02:34:56 am »
Ahhh, yes, I see now - thanks for that.

I had misunderstood the docs, assuming that literals had to be within quotes. Now I see that everything is treated as a literal unless it's a format char, and they need to be quoted if they're to be used as a literal.

Thanks again

 

TinyPortal © 2005-2018