Inverse function of FormatDateTime

后端 未结 7 624
自闭症患者
自闭症患者 2021-02-07 04:38

I am looking for a function to reverse any string (YYYYMDD,YY/MM/DD,YYMMDD,...) created by the function FormatDateTime to

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-07 05:24

    Note: Unfortunately, as pointed out by Martien in this answer's comments, this solution will not work for cases where the date includes no date separator. However, I'm going to leave the answer up for anyone that may find it useful regardless.

    I liked Tuncay's answer but there were a couple of problems with it. I'd have left a comment but I don't have enough reputation points.

    So, here's the corrected version of Tuncay's answer (amending "TFormatSetting" missing an "s" and specified the format settings date separator):

    function AnyStringToDate(fmt, dt: String) : TDateTime;
    var
      fs : TFormatSettings;
    Begin
      fs := TFormatSettings.Create;
      fs.DateSeparator := '-';
      fs.ShortDateFormat := fmt;
    
      result := StrToDateDef(dt, 0, fs);
    End;
    

    Identical to Tuncay's answer, AnyStringToDate can be used as follows:

    mydate := AnyStringToDate('YYYY-MM-DD', '2015-01-20');
    

提交回复
热议问题