码迷,mamicode.com
首页 > 其他好文 > 详细

修改操作系统时间

时间:2015-01-23 17:49:44      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

 

 

    internal class LocalTimeHelper
    {
        [StructLayout(LayoutKind.Sequential)]
        struct SystemTime
        {
            public UInt16 Year;
            public UInt16 Month;
            public UInt16 DayOfWeek;
            public UInt16 Day;
            public UInt16 Hour;
            public UInt16 Minute;
            public UInt16 Second;
            public UInt16 Millisecond;

            public DateTime ToDateTime()
            {
                return new DateTime(Year, Month, Day, Hour, Minute, Second, Millisecond);
            }

            public SystemTime FromDateTime(DateTime value)
            {
                Year = (UInt16)value.Year;
                Month = (UInt16)value.Month;
                Day = (UInt16)value.Day;
                Hour = (UInt16)value.Hour;
                Minute = (UInt16)value.Minute;
                Second = (UInt16)value.Second;
                Millisecond = (UInt16)value.Millisecond;

                return this;
            }

            public static implicit operator DateTime(SystemTime value)
            {
                return value.ToDateTime();
            }

            public static implicit operator SystemTime(DateTime value)
            {
                return new SystemTime().FromDateTime(value);
            }
        }

        [DllImport("kernel32.dll")]
        static extern int SetSystemTime(ref SystemTime systemTime);
        [DllImport("Kernel32.dll")]
        static extern void GetSystemTime(ref SystemTime sysTime);

        public static bool SetSystemLocalTime(DateTime value)
        {
            SystemTime time = value.ToUniversalTime();
            var res = SetSystemTime(ref time);
            return res != 0;
        }

        public static DateTime GetSystemLocalTime()
        {
            var time = new SystemTime();
            GetSystemTime(ref time);
            DateTime res = ((DateTime)time).ToLocalTime();

            return res;
        }
    }

 

修改操作系统时间

标签:

原文地址:http://www.cnblogs.com/baiqjh/p/4244680.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!