To get or set the system time of the device, use platform invoke to call the native GetSystemTime or SetSystemTime functions.
Note that the GetSystemTime function returns Coordinated Universal Time (UTC, also known as Greenwich Mean Time). To get your local time, you must add or subtract the number of hours between your time zone and UTC. For example, 24:00 (midnight) in UTC is 19:00 in New York--an offset of minus 5 hours (UTC–5).
To determine the UTC offset for your time zone, see the Time Zone tab of Date and Time Properties.
Some device emulators do not initially set daylight-saving time correctly, which could affect your result.
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());
}
No comments:
Post a Comment