How to get DateTime from the internet?

Viewed 103212

How to get current date and time from internet or server using C#? I am trying to get time as follows:

public static DateTime GetNetworkTime (string ntpServer)
{
    IPAddress[] address = Dns.GetHostEntry(ntpServer).AddressList;

    if (address == null || address.Length == 0)
        throw new ArgumentException("Could not resolve ip address from '" + ntpServer + "'.", "ntpServer");

    IPEndPoint ep = new IPEndPoint(address[0], 123);
    return GetNetworkTime(ep);
}

I am passing server IP address as netServer, but it does not work properly.

6 Answers
    public static Nullable<DateTime> GetDateTime()
    {
        Nullable<DateTime> dateTime = null;
        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://www.microsoft.com");
        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 System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
        try
        {
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string todaysDates = response.Headers["date"];

                dateTime = DateTime.ParseExact(todaysDates, "ddd, dd MMM yyyy HH:mm:ss 'GMT'",
                    System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat, System.Globalization.DateTimeStyles.AssumeUniversal);
            }
        }
        catch
        {
            dateTime = null;
        }
        return dateTime;
    }
Related