using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Mesnac.Basic
{
public class LocalTime
{
//设定,获取系统时间,SetSystemTime()默认设置的为UTC时间,比北京时间少了8个小时。
[DllImport("Kernel32.dll")]
private static extern bool SetSystemTime(ref SystemTime time);
[DllImport("Kernel32.dll")]
private static extern bool SetLocalTime(ref SystemTime time);
[DllImport("Kernel32.dll")]
private static extern void GetSystemTime(ref SystemTime time);
[DllImport("Kernel32.dll")]
private static extern void GetLocalTime(ref SystemTime time);
//struct for date/time apis
private 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;
}
public void Set(DateTime dt)
{
SystemTime time = new SystemTime();
time.wYear = (ushort)dt.Year;
time.wMonth = (ushort)dt.Month;
time.wDayOfWeek = (ushort)dt.DayOfWeek;
time.wDay = (ushort)dt.Day;
time.wHour = (ushort)dt.Hour;
time.wMinute = (ushort)dt.Minute;
time.wSecond = (ushort)dt.Second;
time.wMilliseconds = (ushort)dt.Millisecond;
SetLocalTime(ref time);
}
///
/// 设置本地系统时间
///
/// 能够转换为时间格式的字符串变量
/// 设置成功返回true,否则返回false
public static bool SetLocalTimeByStr(string timestr)
{
bool flag = false;
SystemTime sysTime = new SystemTime();
DateTime dt = Convert.ToDateTime(timestr);
sysTime.wYear = Convert.ToUInt16(dt.Year);
sysTime.wMonth = Convert.ToUInt16(dt.Month);
sysTime.wDay = Convert.ToUInt16(dt.Day);
sysTime.wHour = Convert.ToUInt16(dt.Hour);
sysTime.wMinute = Convert.ToUInt16(dt.Minute);
sysTime.wSecond = Convert.ToUInt16(dt.Second);
try
{
flag = SetLocalTime(ref sysTime);
}
catch (Exception e)
{
ICSharpCode.Core.LoggingService.Error("SetSystemDateTime函数执行异常:" + e.Message);
}
return flag;
}
}
}