Here's the one I have been using. I make my devices sync up the first time the database object is initiated.
#if PocketPC
[DllImport("coredll.dll")]
#else
[DllImport("kernel32.dll")]
#endif
private static extern bool SetLocalTime([In] ref SYSTEMTIME lpLocalTime);
...and yes, I use the same code for my Windows PCs as for my WinMobile PCs.
This NODATE
variable is global to my entire project, and is defined as Jan. 1, 1900. Hopefully, nothing at this company happened on that date in the SQL Server!
Start with a structure:
/// <summary>
/// SYSTEMTIME structure with some useful methods
/// </summary>
public struct SYSTEMTIME {
public short Year, Month, DayOfWeek, Day, Hour, Minute, Second, Millisecond;
/// <summary>
/// Convert form System.DateTime
/// </summary>
/// <param name="time">Creates System Time from this variable</param>
public void FromDateTime(DateTime time) {
Year = (short)time.Year;
Month = (short)time.Month;
DayOfWeek = (short)time.DayOfWeek;
Day = (short)time.Day;
Hour = (short)time.Hour;
Minute = (short)time.Minute;
Second = (short)time.Second;
Millisecond = (short)time.Millisecond;
}
/// <summary>
/// Convert to System.DateTime
/// </summary>
public DateTime ToDateTime() {
return new DateTime(Year, Month, Day, Hour, Minute, Second, Millisecond);
}
/// <summary>
/// STATIC: Convert to System.DateTime
/// </summary>
public static DateTime ToDateTime(SYSTEMTIME time) {
return time.ToDateTime();
}
}
Then just use that structure like I do in this method that makes the call (I sync with our SQL Server).
/// <summary>
/// Synchronize the Time on the SQL Server with the time on the device
/// </summary>
public static int SyncWithSqlTime() { // pass in SQL Time and set time on device
SYSTEMTIME st = new SYSTEMTIME();
DateTime sqlTime = Global.NODATE;
using (SqlCommand cmd = new SqlCommand("SELECT GETDATE() AS CurrentDateTime;", new SqlConnection(DataSettings.DatabaseConnectionString))) {
try {
cmd.Connection.Open();
SqlDataReader r = cmd.ExecuteReader();
while (r.Read()) {
if (!r.IsDBNull(0)) {
sqlTime = (DateTime)r[0];
}
}
} catch (Exception) {
return -1;
}
}
if (sqlTime != Global.NODATE) {
st.FromDateTime(sqlTime); // Convert to SYSTEMTIME
if (SetLocalTime(ref st)) { //Call Win32 API to set time
return 1;
}
}
return 0;
}
That last if
condition at the bottom is where I set the time using SetLocalTime
.
Hope this gets you somewhere,
~Joe