Last active
August 29, 2015 14:19
-
-
Save suakig/e3879cadbc28f88ed9cb to your computer and use it in GitHub Desktop.
DateTimeNist.cs
This file contains hidden or 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
using System; | |
using System.Net; | |
using System.Net.Cache; | |
using System.IO; | |
using System.Text.RegularExpressions; | |
public class DateTimeNist | |
{ | |
public static DateTime Now | |
{ | |
get{ | |
//エラーが起きた場合はDateTime.MinValueが帰る | |
DateTime dateTime = DateTime.MinValue; | |
HttpWebRequest request = (HttpWebRequest)WebRequest.Create ("http://nist.time.gov/actualtime.cgi?lzbc=siqm9b"); | |
request.Method = "GET"; | |
request.Accept = "text/html, application/xhtml+xml, */*"; | |
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"; | |
request.ContentType = "application/x-www-form-urlencoded"; | |
request.CachePolicy = new RequestCachePolicy (RequestCacheLevel.NoCacheNoStore); //No caching | |
request.Timeout = 5 * 1000; | |
try { | |
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); | |
if (response.StatusCode == HttpStatusCode.OK) { | |
StreamReader stream = new StreamReader (response.GetResponseStream ()); | |
string html = stream.ReadToEnd ();//<timestamp time="\"1395772696469995\"" delay="\"1395772696469995\"/"> | |
string time = Regex.Match (html, @"(?<=\btime="")[^""]*").Value; | |
double milliseconds = Convert.ToInt64 (time) / 1000.0; | |
dateTime = new DateTime (1970, 1, 1).AddMilliseconds (milliseconds).ToLocalTime (); | |
} | |
} | |
catch(System.Net.WebException ex) { | |
//HTTPプロトコルエラーかどうか調べる | |
if (ex.Status == System.Net.WebExceptionStatus.ProtocolError) { | |
//HttpWebResponseを取得 | |
System.Net.HttpWebResponse errres = (System.Net.HttpWebResponse)ex.Response; | |
//応答したURIを表示する | |
Debug.Log ("errres.ResponseUri" + errres.ResponseUri); | |
//応答ステータスコードを表示する | |
Debug.Log (errres.StatusCode + ":" + errres.StatusDescription); | |
} else { | |
Debug.Log ("errres.ResponseUri" + ex.Message); | |
} | |
} | |
return dateTime; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment