How to Change system time in C#
By FoxLearn 1/9/2025 8:41:47 AM 287
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#