{显示和判断单元} unit DBDateEditMaskTrans; interface uses Windows, SysUtils, Controls, Forms,Db;
{日期型字段显示过程,在OnGetText事件中调用} PRocedure DateFieldGetText(Sender: TField; var Text: String);
{日期型字段输入判断函数,在OnSetText事件中调用} function DateFieldSetText(Sender: TField; const Text: String):Boolean;
implementation
procedure DateFieldGetText(Sender: TField; var Text: String); var dDate:TDate; wYear,wMonth,wDay:Word; aryTestYMD:Array [1..2] of Char ;{测试输入掩码用临时数组} iYMD:Integer; begin dDate:=Sender.AsDateTime; DecodeDate(dDate,wYear,wMonth,wDay); {测试输入掩码所包含的格式.} aryTestYMD:=’年’; if StrScan(PChar(Sender.EditMask), aryTestYMD[1])< >nil then iYMD:=1; aryTestYMD:=’月’; if StrScan(PChar(Sender.EditMask), aryTestYMD[1])< >nil then iYMD:=2; aryTestYMD:=’日’; if StrScan(PChar(Sender.EditMask), aryTestYMD[1])< >nil then iYMD:=3;
case iYMD of 1:{输入掩码为:”yyyy年”的格式.} Text:=IntToStr(wYear)+’年’; 2: {输入掩码为:”yyyy年mm月”的格式.} Text:=IntToStr(wYear)+’年’+IntToStr(wMonth)+’月’; 3: {输入掩码为:”yyyy年mm月dd日”的格式.} Text:=IntToStr(wYear)+’年’+IntToStr(wMonth)+’月’ +IntToStr(wDay)+’日’; else {默认为:”yyyy年mm月dd日”的格式.} Text:=IntToStr(wYear)+’年’+IntToStr(wMonth)+’月’ +IntToStr(wDay)+’日’; end;
end;
function DateFieldSetText(Sender: TField; const Text: String):Boolean; var dDate:TDate; sYear,sMonth,sDay:String; aryTestYMD:Array [1..2] of Char; iYMD:Integer; begin {获得用户输入的日期} sYear:=Copy(Text,1,4); sMonth:=Copy(Text,7,2); SDay:=Copy(Text,11,2);
{测试输入掩码所包含的格式.} aryTestYMD:=’年’; if StrScan(PChar(Sender.EditMask), aryTestYMD[1])< >nil then iYMD:=1; aryTestYMD:=’月’; if StrScan(PChar(Sender.EditMask), aryTestYMD[1])< >nil then iYMD:=2; aryTestYMD:=’日’; if StrScan(PChar(Sender.EditMask), aryTestYMD[1])< >nil then iYMD:=3;
{利用Try…Except进行输入的日期转换} try begin case iYMD of 1: {输入掩码为:”yyyy年”的格式.} begin dDate:=StrToDate(sYear+’-01-01’) ;{中文Windows默认的日期格式为:yyyy-mm-dd.下同} Sender.AsDateTime:=dDate; end; 2: {输入掩码为:”yyyy年mm月”的格式.} begin dDate:=StrToDate(sYear+’-’+sMonth+’-01’); Sender.AsDateTime:=dDate; end; 3: {输入掩码为:”yyyy年mm月dd日”的格式.} begin dDate:=StrToDate(sYear+’-’+sMonth+’-’+sDay); Sender.AsDateTime:=dDate; end; else {默认为:”yyyy年mm月dd日”的格式.} begin dDate:=StrToDate(sYear+’-’+sMonth+’-’+sDay); Sender.AsDateTime:=dDate; end; end; DateFieldSetText:=True; end; except {日期转换出错} begin application.MessageBox(PChar(Text+’不是有效的日期!’), ’错误’,mb_Ok+mb_IconError); DateFieldSetText:=False; end; end;
end;
end.
{主窗口单元} unit Main;
interface
uses ……{略去其他内容} procedure Table1BirthdayGetText(Sender: TField; var Text: String;DisplayText: Boolean); procedure Table1BirthdaySetText(Sender: TField; const Text: String); private { Private declarations } public { Public declarations } ……{略} implementation