Converting string to TDateTime in C++Builder 2009

6.3k Views Asked by At

I try to convert strings in specific formats to TDateTime using C++Builder 2009:

TDateTime dt, dt2;
TFormatSettings FS, FS2;

UnicodeString datestring = "17/10/2017 13:24:33";
UnicodeString datestring2 = "2017.17.10 13:24:33";

FS.DateSeparator = '/';
FS.ShortDateFormat = "dd/mm/yyyy";
FS.LongTimeFormat = "hh:nn:ss";
FS.TimeSeparator = ':';

FS2.DateSeparator = '.';
FS2.ShortDateFormat = "yyyy.dd.mm";
FS2.LongTimeFormat = "hh:nn:ss";
FS2.TimeSeparator = ':';

try{
    dt = StrToDateTime(datestring, FS);
    dt2 = StrToDateTime(datestring2,FS2);
}catch(EConvertError& e)
{
    int a = 2;
}

Conversion of dt is ok, but conversion of dt2 throws an exception :

''2017.17.10 13:24:33'' is not a valid date and time

2

There are 2 best solutions below

0
On BEST ANSWER

Thank you all!

Ok now I know that, this date formats are unsupported by StrToDateTime. Solution of this problem is, convert and merge Windows ShortDateFormat and LongTimeFormat to format string accepted by strptime() from time.h. Then I use strptime() and create TDateTime from tm struct from time.h. I try to link docs but, in docs isn't any strptime func. I find this func in time.h from CodeGear RTL ver 13. I think this is equivalent to strptime

3
On

Per the documentation of StrToDate() (which also applies to StrToDateTime()):

S must consist of two or three numbers, separated by the character defined by the DateSeparator global variable or its TFormatSettings equivalent. The order for month, day, and year is determined by the ShortDateFormat global variable or its TFormatSettings equivalent--possible combinations are m/d/y, d/m/y, and y/m/d.

The date that is failing is in y/d/m format, which these RTL functions do not support. The date that works is in d/m/y format, which is supported.