首页  编辑  

Delphi和C#中时间Tick的转换

Tags: /C#/其他技巧/   Date Created:

const

 DaysToMonth : array [ Boolean , 0 .. 12 ] of Integer =

(

( 0 , $1f , $3b , 90 , 120 , $97 , $b5 , $d4 , $f3 , $111 , $130 , $14e , $16d ), //365

( 0 , $1f , 60 , $5b , $79 , $98 , $b6 , $d5 , $f4 , $112 , $131 , $14f , $16e ) //366

);

function DateToTicks ( year , month , day : Integer ): Int64 ;

var

 num , num2 : Integer ;

begin

 Result := 0 ;

  if (( year >= 1 ) and ( year <= $270f )) and (( month >= 1 ) and ( month <= 12 )) then

  begin

    if ( day >= 1 ) and ( day <= ( DaysToMonth [ IsLeapYear ( year )][ month ] -

     DaysToMonth [ IsLeapYear ( year )][ month - 1 ])) then

    begin

     num := year - 1 ;

     num2 := (((((( num * $16d ) + ( num div 4 )) - ( num div 100 )) +

        ( num div 400 )) + DaysToMonth [ IsLeapYear ( year )][ month - 1 ]) + day ) - 1 ;

     Result := num2 * $c92a69c000 ;

    end ;

  end ;

end ;

function TimeToTicks ( hour , minute , second , millisecond : Integer ): Int64 ;

var

 num : Int64 ;

begin

 Result := 0 ;

  if ((( hour < 0 ) or ( hour >= $18 )) or (( minute < 0 ) or ( minute >= 60 ))) or

    (( second < 0 ) or ( second >= 60 )) then Exit ;

 num := (( hour * $e10 ) + ( minute * 60 )) + second ;

 Result := num * $989680 + Int64 ( millisecond * $989680 ) div 1000 ;

end ;

procedure TForm1 . Button1Click ( Sender : TObject );

var

 year , month , day ,

 hour , minute , second , millisecond : Word ;

 tick : Int64 ;

begin

 DecodeDate ( Now , year , month , day );

 DecodeTime ( Now , hour , minute , second , millisecond );

 tick := DateToTicks ( year , month , day ) +

   TimeToTicks ( hour , minute , second , millisecond );

 Caption := IntToStr ( tick );

end ;