如何把类似 2012年3月20日 转换为TDateTime 类型?

解决方案 »

  1.   

    由于客户有可能按他自己的需要而设置了系统日期的格式,同时,也可能因“2012年3月20日”这样的字符中存在空格等等,所以,我弄了这么个函数来处理:function GetDateTime(s: String; var dt: TDateTime): boolean;
    var  buf:pchar;
         len,i:integer;
         sysstr,tmp,Delimiter,yy,mm,dd:string;
    begin
      Result := false;
      //取当前系统日期格式:
      getmem(buf,512);
      len:=512;
      GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SSHORTDATE,buf,len);
      sysstr:=string(buf);
      FreeMem(buf);
      //取出格式中的分隔符:
      Delimiter:='.';
      if pos('-',sysstr)>0 then Delimiter:='-'
      else if pos('/',sysstr)>0 then Delimiter:='/';
      //去除参数中的所有空格
      tmp:=StringReplace(s,' ','',[rfReplaceAll]);
      //分别取出参数中的年、月、日的值:
      yy:='';
      mm:='';
      dd:='';
      i:=1;
      try
        while length(tmp)>0 do begin
          if not(tmp[i]in['0'..'9'])then begin
            if tmp[i]+tmp[i+1]='年' then begin
              yy:=copy(tmp,1,i-1);
              Delete(tmp,1,i+1);
              i:=1;
            end
            else if tmp[i]+tmp[i+1]='月' then begin
              mm:=copy(tmp,1,i-1);
              Delete(tmp,1,i+1);
              i:=1;
            end
            else if tmp[i]+tmp[i+1]='日' then begin
              dd:=copy(tmp,1,i-1);
              Delete(tmp,1,i+1);
              i:=1;
            end;
          end
          else inc(i);
        end;
        if (yy='')or(mm='')or(dd='') then exit;//防止参数不规范
        tmp:=yy+Delimiter+mm+Delimiter+dd;//按系统格式拼日期串
        dt:=StrToDateTime(tmp);//转成日期时间类型
        Result:=true;
      except
      end;
    end;
    //应用例子:
    procedure TForm1.Button1Click(Sender: TObject);
    var d: TDateTime;
    begin
      DateTimePicker1.DateTime:=date;
      DateTimePicker2.DateTime:=date;
      DateTimePicker3.DateTime:=date;
      if GetDateTime('  2012 年 3 月 20 日 ',d) then
        DateTimePicker1.DateTime:=d;
      if GetDateTime(' 3 月 20 日 2012 年',d) then
        DateTimePicker2.DateTime:=d;
      if GetDateTime('2 0 日 3 月 2 0 1 2 年  ',d) then
        DateTimePicker3.DateTime:=d;
    end;