How to get current date and time from internet in C#
By Tan Lee Published on Nov 09, 2024 1.37K
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 } }
Categories
Popular Posts
Structured Data using FoxLearn.JsonLd
Jun 20, 2025
Implement security headers for an ASP.NET Core
Jun 24, 2025
10 Common Mistakes ASP.NET Developers Should Avoid
Dec 16, 2024
Star Admin Dashboard Template
Nov 14, 2024
Monster Admin Template
Nov 14, 2024