2013-10-18 73 views
-3

我已使用以下程序更改系統日期時間。在C#中更改系統日期時間.Date已更改,但TIme未在64位Windows Server 2008中更改

public struct SystemTime 
{ 
    public ushort Year; 
    public ushort Month; 
    public ushort DayOfWeek; 
    public ushort Day; 
    public ushort Hour; 
    public ushort Minute; 
    public ushort Second; 
    public ushort Millisecond; 
}; 

[DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)] 
public extern static void Win32GetSystemTime(ref SystemTime sysTime); 

[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)] 
public extern static bool Win32SetSystemTime(ref SystemTime sysTime); 

private void button1_Click(object sender, EventArgs e) 
{`enter code here` 
    // Set system date and time 
    SystemTime updatedTime = new SystemTime(); 
    updatedTime.Year = (ushort)2009; 
    updatedTime.Month = (ushort)3; 
    updatedTime.Day = (ushort)16; 
    updatedTime.Hour = (ushort)10; 
    updatedTime.Minute = (ushort)0; 
    updatedTime.Second = (ushort)0; 
    // Call the unmanaged function that sets the new date and time instantly 
    Win32SetSystemTime(ref updatedTime); 
} 

系統日期改變但時間不變。 我的任務是讓NTP服務器時間和更改系統的日期和時間,NTP服務器time.Im的獲取NTP服務器的日期和時間&改變日期,但林不能夠改變我的系統的時間

+0

「討論板」並不適合與C#相關的編程問題。請使用實際適用於您提問的問題的標籤,以便它們能夠正確分類以進行搜索,並獲得可能幫助您獲得答案的人員的關注。不要無緣無故地抓取隨機標籤。謝謝。 –

+1

可能的重複[我無法讓SetSystemTime在Windows Vista中使用C#與Interop(P/Invoke)]工作(http://stackoverflow.com/questions/2486125/i-cant-get-setsystemtime-to-work -in-windows-vista-using-c-sharp-with-interop-p) –

+0

是不是正在同步到內置於Windows的NTP服務器? –

回答

1

你聲明SetSystemTime()正確,但您忘記正確使用它。你不能忽略返回值。修復:

if (!Win32SetSystemTime(ref updatedTime)) { 
     throw new System.ComponentModel.Win32Exception(); 
    } 

您現在可以發現異常可能的原因。幾種可能性,但我們可以猜測:更改時鐘需要管理員權限,您的程序不可能擁有它們。您必須要求用戶許可才能執行此操作,只需嵌入要求提供UAC的清單即可。 This answer顯示瞭如何做到這一點。

以防萬一你認爲這是不合理的:請記住,更改時鐘是非常中斷運行程序。在Windows中運行的許多基本服務都依賴於精確的時鐘。它不會持續很長時間,Windows會定期聯繫時間服務器以重新校準時鐘。你必須禁用它,請通過superuser.com詢問。您將遇到的其他問題,例如文件寫入的時間戳不準確,計劃的任務沒有按時運行,Web瀏覽器抱怨不正確的證書,您的項目始終在重建,儘管您沒有做出任何更改,但是您仍然需要處理。不要這樣做。

+0

在我的程序中,它正在改變,但在系統中它沒有顯示。這裏有一個有趣的點是日期改變,我可以看到在我的system.im在Windows Server 2008中運行此。 – user2894119

+0

ntp服務器時間接收爲UTC因此我的系統採用utc + 5:30.如何將ntp服務器時間視爲本地時間。 – user2894119