Delphi 字符串轉日期,強大到窒息,VarToDateTime 解決了 困擾很久的小問題


procedure THRForm.Button1Click(Sender: TObject);
var
  D:TDateTime;
  s:string;
begin
  D:=VarToDateTime('05-10-14 04:35PM');
  S:=FormatDatetime('YYYY-MM-DD HH:MM:SS',D);
  showmessage(s);
end;

 

尤其是在進行數據庫語句操作時,對於字符串的來源不確定因素太多,有了該函數用起來真的很方便。舉例如下:

用VarToDateTime構建一個新的函數SetFieldDate,然后使用該函數為數據庫時間字段賦值,只需

FQuery.Parameters.ParamValues['Brithday'] := SetFieldDate(edit1.Text);
function SetFieldDate(str: string): Variant;
begin
  if str = '' then
    result := Null
  else
    result := StrToDateTime(FormatDatetime('YYYY-MM-DD', VarToDateTime(str)));
end;

 

當然上述函數也可以簡化為:

1 function SetFieldDate(str: string): Variant;
2 begin
3   if str = '' then
4     result := Null
5   else
6     result := VarToDateTime(str);
7 end;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM