You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lj_plc/Main/Mesnac.Basic/SetLocalTime.cs

76 lines
2.7 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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);
}
/// <summary>
/// 设置本地系统时间
/// </summary>
/// <param name="timestr">能够转换为时间格式的字符串变量</param>
/// <returns>设置成功返回true否则返回false</returns>
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<LocalTime>.Error("SetSystemDateTime函数执行异常:" + e.Message);
}
return flag;
}
}
}