forked from yanw/App_win_iot_V2.0
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
84 lines
2.7 KiB
84 lines
2.7 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Runtime.InteropServices;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace IOTContainer.Common
|
|
{
|
|
public class SyncServerTime
|
|
{
|
|
internal 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;
|
|
|
|
/// <summary>
|
|
/// 从System.DateTime转换。
|
|
/// </summary>
|
|
/// <param name="time">System.DateTime类型的时间。</param>
|
|
public void FromDateTime(DateTime time)
|
|
{
|
|
wYear = (ushort)time.Year;
|
|
wMonth = (ushort)time.Month;
|
|
wDayOfWeek = (ushort)time.DayOfWeek;
|
|
wDay = (ushort)time.Day;
|
|
wHour = (ushort)time.Hour;
|
|
wMinute = (ushort)time.Minute;
|
|
wSecond = (ushort)time.Second;
|
|
wMilliseconds = (ushort)time.Millisecond;
|
|
}
|
|
/// <summary>
|
|
/// 转换为System.DateTime类型。
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public DateTime ToDateTime()
|
|
{
|
|
return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);
|
|
}
|
|
/// <summary>
|
|
/// 静态方法。转换为System.DateTime类型。
|
|
/// </summary>
|
|
/// <param name="time">SYSTEMTIME类型的时间。</param>
|
|
/// <returns></returns>
|
|
public static DateTime ToDateTime(SYSTEMTIME time)
|
|
{
|
|
return time.ToDateTime();
|
|
}
|
|
}
|
|
internal class Win32API
|
|
{
|
|
[DllImport("Kernel32.dll")]
|
|
public static extern bool SetLocalTime(ref SYSTEMTIME Time);
|
|
[DllImport("Kernel32.dll")]
|
|
public static extern void GetLocalTime(ref SYSTEMTIME Time);
|
|
}
|
|
public class SystemHelper
|
|
{
|
|
public static void SetLocalMachineTime(DateTime dt)
|
|
{
|
|
try
|
|
{
|
|
//转换System.DateTime到SYSTEMTIME
|
|
SYSTEMTIME st = new SYSTEMTIME();
|
|
st.FromDateTime(dt);
|
|
//调用Win32 API设置系统时间
|
|
Win32API.SetLocalTime(ref st);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
|
|
Log.MyLog.WriteLogFile($"SetLocalMachineTime:{ex.ToString()}");
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|