您的位置:首页 > 编程语言 > C#

C#修改系统时间

2014-06-05 08:27 267 查看
main:

class Program

{

static string input;

static UpdateHelper updTime;

static void Main(string[] args)

{

Console.WriteLine("START APPLICATION!");

//获取当前时间

DateTime today = System.DateTime.Now;

//要变更的时间

DateTime beforeDate = new DateTime(2010,01,01);

updTime = new UpdateHelper();

bool res = updTime.UpdateDateTime(beforeDate);

Console.WriteLine(beforeDate.ToString());

//调用lingoes

Process myProcess = new Process();

try

{

myProcess.StartInfo.UseShellExecute = false;

myProcess.StartInfo.FileName = @"D:\tools\Translator\Lingoes.exe";

myProcess.StartInfo.CreateNoWindow = true;

myProcess.Start();

}

catch(Exception e) {

Console.WriteLine("系统找不到指定的程序文件。\r{0}", e);

return;

}

//休眠

System.Threading.Thread.Sleep(3000);

//还原当前时间

updTime = new UpdateHelper();

bool res1 = updTime.UpdateDateTime(today);

Console.WriteLine(today.ToString());

//END

Console.WriteLine("入力Enter終了!");

input = Console.In.ReadLine();

//System.Console.WriteLine(input);

}

}

updateDate:

public class UpdateHelper

{

[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;

//设置系统时间参数

public void FromDateTime(DateTime dateTime)

{

wYear = (ushort)dateTime.Year;

wMonth = (ushort)dateTime.Month;

wDayOfWeek = (ushort)dateTime.DayOfWeek;

wDay = (ushort)dateTime.Day;

wHour = (ushort)dateTime.Hour;

wMinute = (ushort)dateTime.Minute;

wSecond = (ushort)dateTime.Second;

wMilliseconds = (ushort)dateTime.Millisecond;

}

//获取系统时间

public DateTime ToDateTime()

{

return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond);

}

}

//设定,获取系统时间,SetSystemTime()默认设置的为UTC时间,比北京时间少了8个小时因此我们只用LocalTime。

[DllImport("Kernel32.dll")]

public static extern bool SetSystemTime(ref SYSTEMTIME time);

[DllImport("Kernel32.dll")]

public static extern bool SetLocalTime(ref SYSTEMTIME time);

[DllImport("Kernel32.dll")]

public static extern void GetSystemTime(ref SYSTEMTIME time);

[DllImport("Kernel32.dll")]

public static extern void GetLocalTime(ref SYSTEMTIME time);

/// <summary>

/// 修改系统日期时间

/// </summary>

/// <param name="datetime">新日期时间</param>

/// <returns>修改是否成功</returns>

public bool UpdateDateTime(DateTime datetime) //修改系统时间

{

SYSTEMTIME st = new SYSTEMTIME();

st.FromDateTime(datetime);

bool res = SetLocalTime(ref st);

return res;

/*COleDateTime tm;

SYSTEMTIME st;

tm.ParseDateTime("2007-11-24 8:00:00");

tm.GetAsSystemTime(st);

SetLocalTime(&st);*/

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: