HOW TO:取得或設定系統時間

更新:2007 年 11 月

若要取得或設定裝置的系統時間,可使用平台叫用 (Invoke) 來呼叫原生 GetSystemTimeSetSystemTime 函式。

請注意,GetSystemTime 函式會傳回 Coordinated Universal Time (UTC,也稱為格林威治標準時間)。若要取得本地時間,必須加減您的時區和 UTC 之間的時數差。例如,UTC 時間 24:00 (午夜) 是紐約的 19:00,之間的時數差為 5 小時 (UTC–5)。

若要判斷所在時區的 UTC 位移量,請參閱 [日期與時間] 屬性的 [時區] 索引標籤。

某些裝置模擬器一開始不會正確設定日光節約時間,這也會影響結果。

範例

這個程式碼範例定義下列作業:

  • Windows Embedded CE 中原生方法的平台叫用宣告。

  • 用以從原生方法傳送和接收的結構

  • 名為 GetTime 的 Managed 方法會顯示目前的時間

  • 名為 SetTime 的 Managed 方法會將系統時鐘設定為加一小時

Public Structure SYSTEMTIME
    Public wYear As UInt16
    Public wMonth As UInt16
    Public wDayOfWeek As UInt16
    Public wDay As UInt16
    Public wHour As UInt16
    Public wMinute As UInt16
    Public wSecond As UInt16
    Public wMilliseconds As UInt16
End Structure

Declare Function GetSystemTime Lib "CoreDll.dll" _
    (ByRef lpSystemTime As SYSTEMTIME) As UInt32

Declare Function SetSystemTime Lib "CoreDll.dll" _
    (ByRef lpSystemTime As SYSTEMTIME) As UInt32

Public Sub GetTime
    ' Call the native GetSystemTime method
    ' with the defined structure.
    Dim st As New SYSTEMTIME
    GetSystemTime(st)

    ' Show the current time.
    MessageBox.Show("Current Time: "  & st.wHour.ToString() _
        & ":" & st.wMinute.ToString())
End Sub

Public Sub SetTime
    ' Call the native GetSystemTime method
    ' with the defined structure.
   Dim st As New SYSTEMTIME
    GetSystemTime(st)

    ' Set the system clock ahead one hour.
    st.wHour = Convert.ToUInt16(((CInt(st.wHour) + 1)) Mod 24)
    SetSystemTime(st)

End Sub


[DllImport("coredll.dll")]
private extern static void GetSystemTime(ref SYSTEMTIME lpSystemTime);

[DllImport("coredll.dll")]
private extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);


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

private void GetTime()
{
    // Call the native GetSystemTime method
    // with the defined structure.
    SYSTEMTIME stime = new SYSTEMTIME();
    GetSystemTime(ref stime);

    // Show the current time.           
    MessageBox.Show("Current Time: "  + 
        stime.wHour.ToString() + ":"
        + stime.wMinute.ToString());
}
private void SetTime()
{
    // Call the native GetSystemTime method
    // with the defined structure.
    SYSTEMTIME systime = new SYSTEMTIME();
    GetSystemTime(ref systime);

    // Set the system clock ahead one hour.
    systime.wHour = (ushort)(systime.wHour + 1 % 24);
    SetSystemTime(ref systime);
    MessageBox.Show("New time: " + systime.wHour.ToString() + ":"
        + systime.wMinute.ToString());
}

編譯程式碼

這個範例需要下列命名空間的參考:

請參閱

其他資源

.NET Compact Framework 中的互通性