Get & Set system time in C#

為{幸葍}努か 提交于 2019-12-13 05:25:39

问题


I found one piece of sample code from web forum. When I began to learn it. I found the output is very strange.

Why does the code can't work well?

It always go forward 8 hours when I run the code below.

VS2005 and WinXP used.Thank you.

class Tester
    {
        [System.Runtime.InteropServices.DllImport("kernel32", SetLastError =
        true)]
        private static extern bool GetSystemTime(out SYSTEMTIME systemTime);
        [System.Runtime.InteropServices.DllImport("kernel32", SetLastError =
        true)]
        private static extern bool SetSystemTime(ref SYSTEMTIME systemTime);
        struct SYSTEMTIME
        {
            internal short wYear;
            internal short wMonth;
            internal short wDayOfWeek;
            internal short wDay;
            internal short wHour;
            internal short wMinute;
            internal short wSecond;
            internal short wMilliseconds;
        }
        static void Main()
        {
            SYSTEMTIME st;
            if (GetSystemTime(out st))
            {
                st.wHour = 2;   // new system time was set to nearby 10:00 AM, 2 + 8
                // If i replace the line with below one. 
                // st.wHour = 18;  // new system time was set to nearby 2:00 AM next day, 18 + 8 = 26, 26 - 24. go to next day!
                if (SetSystemTime(ref st))
                    Console.WriteLine("success");
                else
                    Console.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
            }
            else
                Console.WriteLine("GetSystemTime failed: {0}",
                System.Runtime.InteropServices.Marshal.GetLastWin32Error());
        }
    }

回答1:


The system time is returned in UTC - use GetLocalTime instead:

http://msdn.microsoft.com/en-us/library/ms724390(VS.85).aspx




回答2:


GetSystemTime Function

Retrieves the current system date and time. The system time is expressed in Coordinated Universal Time (UTC).

To retrieve the current system date and time in local time, use the GetLocalTime function



来源:https://stackoverflow.com/questions/3138974/get-set-system-time-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!