首页  编辑  

获得网络时间

Tags: /C#/Web网络编成/   Date Created:

string vReturnData = null ;

TcpClient vTcpClient = new TcpClient ();

try

{

   vTcpClient . Connect( "time.nist.gov" , 13 );

    NetworkStream vNetworkStream = vTcpClient . GetStream();

   if (vNetworkStream . CanWrite && vNetworkStream . CanRead)

   {

        byte [] vHello = Encoding . ASCII . GetBytes( "Hello" );

       vNetworkStream . Write(vHello, 0 , vHello . Length);

        byte [] vReceiveBuffer = new byte [vTcpClient . ReceiveBufferSize];

       vNetworkStream . Read(vReceiveBuffer, 0 ,

           ( int )vTcpClient . ReceiveBufferSize);

       vReturnData = Encoding . ASCII . GetString(vReceiveBuffer);

   }

   vTcpClient . Close();

}

catch ( Exception vException)

{

    MessageBox . Show(vException . ToString());

    return ;

}

string [] vTokens = vReturnData . Split( ' ' );

string [] vDates = vTokens[ 1 ] . Split( '-' );

string [] vTimes = vTokens[ 2 ] . Split( ':' );

DateTime vOfficial = new DateTime (

    Int32 . Parse(vDates[ 0 ]) + 2000 , Int32 . Parse(vDates[ 1 ]),

    Int32 . Parse(vDates[ 2 ]), Int32 . Parse(vTimes[ 0 ]),

    Int32 . Parse(vTimes[ 1 ]), Int32 . Parse(vTimes[ 2 ]));

DateTime vlocaltime = TimeZone . CurrentTimeZone . ToLocalTime(vOfficial);

MessageBox . Show(vlocaltime . ToString());