C# Tips

C# Tip Article

How to get the current date and time from internet?

Problem

How to get the current date and time from internet?

Solution

There are two common solutions:
(1) Use NTP (Network Time Protocol) server

// #1 Use NTP
var tcp = new TcpClient("time.nist.gov", 13);
string resp;
using (var rdr = new StreamReader(tcp.GetStream()))
{
	resp = rdr.ReadToEnd();
}

string utc = resp.Substring(7, 17);
var dt = DateTimeOffset.ParseExact(utc, 
           yy-MM-dd HH:mm:ss", 
		   CultureInfo.InvariantCulture, 
		   DateTimeStyles.AssumeUniversal);

(2) Make HTTP request and parse data.

// #2 Use HTTP
static void Main(string[] args)
{
	var dt = GetCurrentTime();
	Console.WriteLine(dt);
}

public static DateTimeOffset? GetCurrentTime()
{
	var sites = new string[] 
	{
		"https://nist.time.gov",
		"http://www.microsoft.com",
		"http://www.google.com"
	};

	foreach (var site in sites)
	{
		try
		{
			var dt = GetTimeFromSite(site);
			if (dt != null)
			{
				return dt;
			}
		}
		catch
		{
			continue;
		}
	}
	return null;
}

private static DateTimeOffset? GetTimeFromSite(string site)
{
	var req = WebRequest.Create(site);
	var resp = req.GetResponse();
	string currTime = resp.Headers["date"];
	var dt = DateTimeOffset.ParseExact(currTime, 
	          "ddd, dd MMM yyyy HH:mm:ss 'GMT'",
			  CultureInfo.InvariantCulture.DateTimeFormat,
			  DateTimeStyles.AssumeUniversal);
	return dt;
}