How to get current date and time from internet in C#

By FoxLearn 11/9/2024 1:57:14 PM   183
In C#, you can retrieve the current date and time from the internet by using a time server (also known as an NTP server) to sync with an accurate time source.

This process generally involves using a library or a custom function to request the current time from an NTP server.

Use NTP (Network Time Protocol) server

var tcp = new TcpClient("time.nist.gov", 13);
string response;
using (var stream = new StreamReader(tcp.GetStream()))
{
    response = stream.ReadToEnd();
}
string utc = response.Substring(7, 17);
var dt = DateTimeOffset.ParseExact(utc,"yy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
Console.WriteLine(dt); // 11/9/2024 1:40:13 PM +00:00

You can create a HTTP request and parse data.

var sites = new string[]
{
    "https://nist.time.gov",
    "http://www.microsoft.com",
    "http://www.google.com"
};
foreach (var site in sites)
{
    var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
    var response = await client.GetAsync(site);
    var headers = response.Headers.GetValues("date").ToList();
    if (headers.Count() > 0)
    {
        var dt = DateTimeOffset.ParseExact(headers[0], "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal);
        Console.WriteLine(dt); // 11/9/2024 1:55:01 PM +00:00
    }
}