How to Change system time in C#
By Tan Lee Published on Nov 05, 2024 539
In C#, the DateTime struct does not have any built-in method to set the system time.
To change the system time, you need to use the Win32 API through P/Invoke.
The SetSystemTime()
API can be used to set a new system time, and GetSystemTime()
retrieves the current system time. Both APIs operate using UTC time, so when setting or retrieving system time, it is essential to handle UTC time correctly.
You can use DateTime.UtcNow
to get the current UTC time in C#.
To change the system time, you would typically define a structure to pass to SetSystemTime()
and call it using P/Invoke as shown below.
// c# datetime set [DllImport("kernel32.dll")] public static extern bool SetSystemTime(ref SYSTEMTIME time); [DllImport("kernel32.dll")] public static extern void GetSystemTime(ref SYSTEMTIME time); [StructLayout(LayoutKind.Sequential)] public struct 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; public SYSTEMTIME(DateTime dt) { Year = (ushort)dt.Year; Month = (ushort)dt.Month; DayOfWeek = (ushort)dt.DayOfWeek; Day = (ushort)dt.Day; Hour = (ushort)dt.Hour; Minute = (ushort)dt.Minute; Second = (ushort)dt.Second; Milliseconds = (ushort)dt.Millisecond; } }
Main method
// Change System Time DateTime date = new DateTime(2024, 11, 5, 12, 30, 15, 0, DateTimeKind.Utc); SYSTEMTIME systime = new SYSTEMTIME(date); SetSystemTime(ref systime); // Get UTC time Console.WriteLine("{0:yyyy-MM-dd hh:mm:ss}", DateTime.UtcNow);
To use SetSystemTime
, your program needs administrative privileges, as changing the system time affects the entire system.
Categories
Popular Posts
HTML Bootstrap 4 Login, Register & Reset Template
Nov 11, 2024
Login SignUp form using HTML CSS JS
Nov 11, 2024
10 Common Mistakes ASP.NET Developers Should Avoid
Dec 16, 2024
DASHMIN Admin Dashboard Template
Nov 16, 2024