主机服务器显示世界时间

本文关键字:世界 时间 显示 服务器 主机服务 主机 | 更新日期: 2023-09-27 18:02:36

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服务器的名称'tritonadmin.com'时,它显示的是UTC时间,而不是我的ntp服务器时间。

主机服务器显示世界时间

您必须像下面的代码示例一样为不同的时区。你必须使用全球化

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