Created
February 22, 2016 15:43
-
-
Save syu5-gh/143b0d904665905d96ea to your computer and use it in GitHub Desktop.
Adjust date and time function using date header from HTTP response for NETMF.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static bool AdjustDateTime() | |
{ | |
try | |
{ | |
var webReq = WebRequest.Create("http://time.windows.com"); | |
webReq.Method = "HEAD"; | |
var webResp = webReq.GetResponse(); | |
Debug.Print("Begin Response."); | |
foreach (var key in webResp.Headers.AllKeys) | |
{ | |
Debug.Print(key + ":" + webResp.Headers[key]); | |
} | |
Debug.Print("End Response."); | |
// Example) Tue, 24 Mar 2015 23:59:14 GMT | |
string dateStr = webResp.Headers["Date"]; | |
webResp.Close(); | |
string[] dateElements = dateStr.Split(new char[] { ' ' }); | |
string tz = dateElements[5]; | |
if (tz != "GMT") | |
{ | |
throw new Exception("Date string is not GMT."); | |
} | |
int day = System.Convert.ToInt32(dateElements[1]); | |
int year = System.Convert.ToInt32(dateElements[3]); | |
var monthStrs = new string[] { | |
"Jan","Feb","Mar","Apr", | |
"May","Jun","Jul","Aug", | |
"Sep","Oct","Nov","Dec" | |
}; | |
int month = Array.IndexOf(monthStrs, dateElements[2]); | |
if (month == -1) | |
{ | |
throw new Exception("Date string cannot be converted."); | |
} | |
month++; | |
var timeElements = dateElements[4].Split(new char[] { ':' }); | |
int hour = System.Convert.ToInt32(timeElements[0]); | |
int minute = System.Convert.ToInt32(timeElements[1]); | |
int second = System.Convert.ToInt32(timeElements[2]); | |
var dateTime = new DateTime(year, month, day, hour, minute, second); | |
Microsoft.SPOT.Hardware.Utility.SetLocalTime(dateTime); | |
} | |
catch (Exception exc) | |
{ | |
Debug.Print("Failed to adjust date. " + exc.Message); | |
return false; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment