c#同步网络时间到本地

c#同步时间

第一种方法:
借用系统接口
[DllImport("user32.dll")]
        private static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);

        [DllImport("Kernel32.dll")]
        private static extern Boolean SetSystemTime([In, Out] SystemTime st);

        [DllImport("Kernel32.dll")]
        public static extern bool SetLocalTime(ref SystemTime st);


        [StructLayout(LayoutKind.Sequential)]
        public class SystemTime
        {
            public ushort year;
            public ushort month;
            public ushort dayofweek;
            public ushort day;
            public ushort hour;
            public ushort minute;
            public ushort second;
            public ushort milliseconds;

        }

然后传入时间,调用接口
 //SystemTime st = new SystemTime();
                //st.year = Convert.ToUInt16(newdatetime.Year);
                //st.month = Convert.ToUInt16(newdatetime.Month);
                //st.day = Convert.ToUInt16(newdatetime.Day);
                //st.dayofweek = Convert.ToUInt16(newdatetime.DayOfWeek);
              
                //    st.hour =
                //        Convert.ToUInt16(newdatetime.Hour -
                //                         TimeZone.CurrentTimeZone.GetUtcOffset(new DateTime(2001,   09, 01)).Hours);

                //st.minute = Convert.ToUInt16(newdatetime.Minute);
                //st.second = Convert.ToUInt16(newdatetime.Second);
                //st.milliseconds = Convert.ToUInt16(newdatetime.Millisecond);

               //return SetSystemTime(st);

在使用过程中,遇到一个问题,未解决,例如:newdatetime为网络返回时间 2013-09-30 06:20:19  这样的话,校准时间后,并非为6点,而是下午14点,但是如果返回时间为 2013-09-30 08:00:00 则校准成功,网络查找原因为时区差,北京为8时区之类的,
第二种方法
引入 Microsoft.VisualBasic

Microsoft.VisualBasic.DateAndTime.Today = newdatetime;
                Microsoft.VisualBasic.DateAndTime.TimeOfDay = newdatetime;

不存在第一种问题

posted @ 2013-09-30 15:54  陈帆  Views(547)  Comments(0Edit  收藏  举报