托管服务器显示世界时

时间:2015-07-14 06:00:43

标签: c# asp.net wcf-data-services

public DateTime GetNetworkTime(string ntpServer)         {

        //const string ntpServer = "tritonadmin.com";
        const int timeout = 2000;

        var ntpData = new byte[48];
        ntpData[0] = 0x1B; //LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)       
        try
        {
            var addresses = Dns.GetHostEntry(ntpServer).AddressList;
            var ipEndPoint = new IPEndPoint(addresses[0], 123);
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            // wait two seconds before timing out
            socket.ReceiveTimeout = timeout;

            socket.Connect(ipEndPoint);
            socket.Send(ntpData);
            var receivedBytes = 0;

            receivedBytes = socket.Receive(ntpData);
            ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | (ulong)ntpData[43];
            ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | (ulong)ntpData[47];

            var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

            var networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds) ;
            socket.Close();


            return networkDateTime;

        }
        catch (SocketException ex)
        {
            DateTime s = new DateTime(1900, 1, 1);
            return s;
        }


    }
Above code is working fine in local host server but when i am hosting the code in windows server then it will show standard time ( Mon, 01 Jan 1900 00:00 ) and also hosting in NTP server and getting the time from own server time it will show utc time not for that system time. 

在NTP服务器中,它会显示某些ntp服务器时间的正确时间,如pool.ntp.org。 但是,当我输入我自己的ntp服务器的名称&#39; tritonadmin.com&#39;它显示UTC时间而不是我的ntp服务器时间。

1 个答案:

答案 0 :(得分:1)

您必须执行以下不同时区的代码示例...您必须使用全球化

using System;
using System.Globalization;
using System.Threading;
public class TestClass
{
   public static void Main()
   {
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

      DateTime dt = DateTime.Now;
      Console.WriteLine("Today is {0}", DateTime.Now.ToString("d"));

      // Increments dt by one day.
      dt = dt.AddDays(1);
      Console.WriteLine("Tomorrow is {0}", dt.ToString("d"));

   }
}

或者

using System;

class Program
{
    static void Main()
    {
    TimeZone zone =  TimeZone.CurrentTimeZone;
    // Demonstrate ToLocalTime and ToUniversalTime.
    DateTime local = zone.ToLocalTime(DateTime.Now);
    DateTime universal = zone.ToUniversalTime(DateTime.Now);
    Console.WriteLine(local);
    Console.WriteLine(universal);
    }
}

通过上面提供的代码,您可以为全世界的应用程序设置特定的标准时间。 有关时区的更多参考,您可以查看 - https://msdn.microsoft.com/en-us/library/5hh873ya(v=vs.71).aspx