字符串转TDateTime的时候,如果格式与系统的长短日期不符合,就会报异常,此时一个通用的解决方法为,软件启动的时候设置软件的长短日期格式,如下图所示:
Application->UpdateFormatSettings = false;
FormatSettings.ShortTimeFormat = "HH:NN:SS";
FormatSettings.ShortDateFormat = "yyyy-mm-dd";
FormatSettings.DateSeparator = '-';
这样,TDateTime dtTmp(“2018-05-01 10:10:10”)或者StrToDateTime(“2018-05-01 10:10:10”); 无论系统的短日期格式是何种格式,软件都不会报错。
但如果日期时间字符串来自其他地方,格式不明确,比如:
TDateTime dtTmp(Query->FiledByName(“FileTime”)->AsString);
如果此时Query检索出来的日期时间格式为"yyyy/mm/dd",则会报EConvertError异常:“xx/xx/xx xx:xx:xx is not a valid date and time”。
为了解决这种问题,可以使用另外一种字符串转TDateTime:
VarToDateTime(String)
此函数兼容长短格式的日期时间字符串,比如2018/05/01 10:10:10 和2018-05-01 10:10:10,但如果字符串是无意义的字符串,比如空字符串或其他字符串,比如“abc”,则会抛出异常:EVariantTypeCastError,Could not convert variant of type (String) into type (Date) 。