'23/02/2011 12:34:56' is not valid date and time

前端 未结 3 757
半阙折子戏
半阙折子戏 2020-12-16 12:59

In my code I am facing a problem. Example code:

var 
    d1: tdatetime
begin
    d1 := strtodatetime(\'23/02/2011 12:34:56\');
end; 

but it

相关标签:
3条回答
  • 2020-12-16 13:37

    Using VarToDateTime might be a lot simpler and it just works out of the box:

    uses Variants;
    
    newDateTime := VarToDateTime('23/02/2011 12:34:56');
    
    0 讨论(0)
  • 2020-12-16 13:41

    the StrToDateTime function uses the ShortDateFormat and DateSeparator to convert the date part and the LongTimeFormat and TimeSeparator to the time part. so you string must match with theses variables to convert the string to TDateTime. instead you can use the StrToDateTime with the TFormatSettings parameter, to parse you string.

     function StrToDateTime(const S: string; const FormatSettings: TFormatSettings): TDateTime; 
    

    check this sample

    Var
    StrDate : string;
    Fmt     : TFormatSettings;
    dt      : TDateTime;
    begin
    fmt.ShortDateFormat:='dd/mm/yyyy';
    fmt.DateSeparator  :='/';
    fmt.LongTimeFormat :='hh:nn:ss';
    fmt.TimeSeparator  :=':';
    StrDate:='23/02/2011 12:34:56';
    dt:=StrToDateTime(StrDate,Fmt);
    
    0 讨论(0)
  • 2020-12-16 13:58

    This is caused by the date/time format in your code not matching the date/time format for your locale settings.

    From the docs (D2009):

    The S parameter must use the current locale's date/time format. In the US, this is commonly MM/DD/YY HH:MM:SS format. Specifying AM or PM as part of the time is optional, as are the seconds. Use 24-hour time (7:45 PM is entered as 19:45, for example) if AM or PM is not specified.

    If you are using an older Delphi, StrToDateTime may require a specific format. From the docs (D5 in this case):

    The S parameter must be in the MM/DD/YY HH:MM:SS format. Specifying AM or PM as part of the time is optional, as are the seconds. Use 24-hour time (7:45 PM is entered as 19:45, for example) if AM or PM is not specified.

    0 讨论(0)
提交回复
热议问题