I am new in programming and I'm practicing with a project and I need a DateTime for it. But as you know windows DateTime can be changed by user so I need a more solid time. So far I found this two different codes. (I don't need local time. I need a time that no matter where your location is it gives you the same time.)
So here is first way to get time :
private void button1_Click(object sender, EventArgs e)
{
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);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
StreamReader stream = new StreamReader(response.GetResponseStream());
string html = stream.ReadToEnd();
string time = Regex.Match(html, @"(?<=\btime="")[^""]*").Value;
double milliseconds = Convert.ToInt64(time) / 1000.0;
textBox1.Text = new DateTime(1970, 1, 1).AddMilliseconds(milliseconds).ToString();
}
Here is the second way :
private void button2_Click(object sender, EventArgs e)
{
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
var response = myHttpWebRequest.GetResponse();
string todaysDates = response.Headers["date"];
DateTime dateTime = DateTime.ParseExact(todaysDates, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal);
textBox2.Text = dateTime.ToString();
response.Close();
}
So here is the questions :
Which one of this codes you recommend me to use? (I really appreciate it if you give me a better code)
Is that code requires any changes?
Is the code no matter what your location is it still gives you the same time?
Is the code always and on every computer works? (I'v read some comments about port 13 and how the code might not work depends on its status)