如何:获取或设置系统时间

更新:2007 年 11 月

若要获取或设置设备的系统时间,请使用平台调用来调用本机 GetSystemTimeSetSystemTime 函数。

注意,GetSystemTime 函数返回协调通用时间(UTC,也称为格林威治时间)。若要获得本地时间,必须加上或减去您所在的时区与 UTC 之间相差的小时数。例如,UTC 中的 24:00(午夜)是纽约的 19:00 -- 负 5 小时的偏移量 (UTC–5)。

若要确定您所在时区的 UTC 偏移量,请参见“日期和时间属性”的“时区”选项卡。

有些设备模拟器起初未正确设置夏时制,从而可能影响结果。

示例

此代码示例定义下面的内容:

  • Windows Embedded CE 中本机方法的平台调用声明。

  • 一个要传递给本机方法并从本机方法接收的结构。

  • 一个名为 GetTime 的托管方法,显示当前时间。

  • 一个名为 SetTime 的托管方法,设置提前一小时的系统时钟。

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 中的互操作性