45 lines
1.3 KiB
C#
45 lines
1.3 KiB
C#
using System.Runtime.InteropServices;
|
|
|
|
namespace RTCSync.Utils;
|
|
|
|
public abstract class WindowsTimeUtils
|
|
{
|
|
// 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, Month, DayOfWeek, Day;
|
|
public ushort Hour, Minute, Second, Milliseconds;
|
|
|
|
public SystemTime() { }
|
|
|
|
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;
|
|
}
|
|
}
|
|
|
|
// Фикс для Windows 7 SP1 без обновлений
|
|
// DataTime.Now использует слишком новый API
|
|
public static DateTime Now()
|
|
{
|
|
var st = new SystemTime();
|
|
GetSystemTime(ref st);
|
|
return new DateTime(st.Year, st.Month, st.Day,
|
|
st.Hour, st.Minute, st.Second, st.Milliseconds,
|
|
DateTimeKind.Utc).ToLocalTime();
|
|
}
|
|
} |