Instantly share code, notes, and snippets.

Embed
What would you like to do?
DateTimeNist.cs
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