首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从时间服务器设置日期/时间

如何从时间服务器设置日期/时间
EN

Stack Overflow用户
提问于 2013-12-16 15:42:50
回答 1查看 1.8K关注 0票数 3

嗨,我正在使用How to Query an NTP Server using C#?的下面的函数从时间服务器获取时间

代码语言:javascript
复制
public  DateTime _MGetNetworkTime()
{
    try
    {
        //default Windows time server
        const string ntpServer = "time.windows.com";

        // NTP message size - 16 bytes of the digest (RFC 2030)
        var ntpData = new byte[48];

        //Setting the Leap Indicator, Version Number and Mode values
        ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)

        var addresses = Dns.GetHostEntry(ntpServer).AddressList;

        //The UDP port number assigned to NTP is 123
        var ipEndPoint = new IPEndPoint(addresses[0], 123);
        //NTP uses UDP
        var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        socket.Connect(ipEndPoint);

        socket.Send(ntpData);
        socket.Receive(ntpData);
        socket.Close();

        //Offset to get to the "Transmit Timestamp" field (time at which the reply 
        //departed the server for the client, in 64-bit timestamp format."
        const byte serverReplyTime = 40;

        //Get the seconds part
        ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);

        //Get the seconds fraction
        ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);

        //Convert From big-endian to little-endian
        intPart = SwapEndianness(intPart);
        fractPart = SwapEndianness(fractPart);

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

        //**UTC** time
        var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);

        return networkDateTime.ToLocalTime();
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
        return Convert.ToDateTime ("12-31-1900");
    }
}

uint SwapEndianness(ulong x)
{
    return (uint)(((x & 0x000000ff) << 24) +
                   ((x & 0x0000ff00) << 8) +
                   ((x & 0x00ff0000) >> 8) +
                   ((x & 0xff000000) >> 24));
}

上述功能正在工作,但我的问题是:

它没有得到印度时间。假设现在的时间是晚上9:10,函数设置在上午5:30,日期是正确的..

请指点我哪里错了。

谢谢

更新:

我正在设置一个日期时间,例如DateTime a = _MGetNetworkTime();,上面的代码,并将值传递给其他函数,如下所示。

代码语言:javascript
复制
[StructLayout(LayoutKind.Sequential)]
        public struct SYSTEMTIME
        {
            public short wYear;
            public short wMonth;
            public short wDayOfWeek;
            public short wDay;
            public short wHour;
            public short wMinute;
            public short wSecond;
            public short wMilliseconds;
        }
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool SetSystemTime(ref SYSTEMTIME st);

        public  void _MSetSystemDate(short _pYear, short _pMonth, short _pDay, short _pHour = 0, short _pMinute = 0, short _pSecond = 0)
        {
            if (IsUserAdministrator())
            {
                SYSTEMTIME st = new SYSTEMTIME();
                st.wYear = _pYear; // must be short
                st.wMonth = _pMonth;
                st.wDay = _pDay;
                st.wHour = _pHour;
                st.wMinute = _pMinute;
                st.wSecond = _pSecond;
                SetSystemTime(ref st); // invoke this method.
            }
            else
            {
                MessageBox.Show("You have not Windows Administrator Access." + Environment.NewLine + "Please Login Windows with Addministrator Rights.");
            }
        }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-16 16:18:03

我相信这也应该在没有任何互联网连接的情况下起作用。试试看:

代码语言:javascript
复制
private static TimeZoneInfo INDIAN_ZONE = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime indianTime =  TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, INDIAN_ZONE);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20614817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档