2

Delphi. I need to convert a datetime string to a TDateTime type. The code I use:

...
var
  fs : TFormatSettings;
  dt: TDateTime;
begin
  fs := TFormatSettings.Create;
  fs.DateSeparator := '-';
  fs.TimeSeparator := ':';
  fs.ShortDateFormat := 'dd-mmm-yy';
  fs.ShortTimeFormat := 'hh:nn:ss';
  dt := StrToDateTime(Timestamp, fs);
...

The string is like this: Timestamp := '26-Feb-16 08:30:00'

I get only convert error messages

EConvertError, '26-Feb-16 08:30:28' is not a valid date and time

If I manually enter a timestamp of format 'yyyy/mm/dd hh:nn:ss' and make ShortDateFormat := 'yyyy/mm/dd'; and ShortTimeFormat := 'hh:nn:ss'; I have no problems...

I don't know what I'm missing? Anyone have a clue?

Tom Brunberg
  • 20,312
  • 8
  • 37
  • 54
chillum
  • 123
  • 1
  • 10
  • 4
    It's always frustrating when you report the fact that you saw an error message, but you don't include its content. That implies to me that you did not read the error message. People often glaze over when they encounter error messages because they assume that they will not understand them, or cannot understand them, or that they convey no useful information, or I don't know what. Anyway, you never know, the error message might be useful. Don't ever omit these details. – David Heffernan Feb 29 '16 at 12:02
  • verstion Delphi 10 Seattle – chillum Feb 29 '16 at 12:11
  • it says convert error :-) EConvertError, '26-Feb-16 08:30:28' is not a valid date and time – chillum Feb 29 '16 at 12:12
  • 1
    An answer I posted [here](http://stackoverflow.com/a/3789628/62576) provides a much easier solution than parsing the date yourself. – Ken White Feb 29 '16 at 15:31

1 Answers1

4

StrToDateTime does not support formats that specify the month as a name, either short or long form.

You will have to parse your text using some other method. Frankly, this format is very easy to parse.

  1. Split the input on the space character to get date and time parts.
  2. Split the date part on - to get day, month and year parts. Search through the 12 short month names to find a match.
  3. Split the time part on : to find hours, minutes and seconds. Or use StrToTime.

Or you could take the input and replace short month names with month numbers and use StrToDateTime with the mm month format.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490