get system time using win32 api in csharp

To get the system time using Win32 API in C#, you can use the GetSystemTime function from the kernel32.dll library. Here's an example:

main.cs
using System;
using System.Runtime.InteropServices;

public class Program
{
    public static void Main()
    {
        SYSTEMTIME st = new SYSTEMTIME();
        GetSystemTime(ref st);
        DateTime dt = new DateTime(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, DateTimeKind.Utc);
        Console.WriteLine(dt);
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct SYSTEMTIME
    {
        public ushort wYear;
        public ushort wMonth;
        public ushort wDayOfWeek;
        public ushort wDay;
        public ushort wHour;
        public ushort wMinute;
        public ushort wSecond;
        public ushort wMilliseconds;
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern void GetSystemTime(ref SYSTEMTIME lpSystemTime);
}
821 chars
30 lines

Explanation:

  1. First, the code defines the necessary namespaces, including System and System.Runtime.InteropServices.
  2. Next, it defines the Program class with a Main method.
  3. Inside the Main method, it declares an instance of the SYSTEMTIME struct and invokes the GetSystemTime API function with a reference to that struct as a parameter.
  4. After that, it creates a new instance of the DateTime struct using the components of the SYSTEMTIME struct, and specifies that it represents a UTC time.
  5. Finally, it prints out the resulting DateTime value to the console.

Note: The GetSystemTime function returns the system time in UTC. You may need to adjust the time zone depending on your requirements.

gistlibby LogSnag