How to get current date and time from internet in C#
By Tan Lee Published on Nov 09, 2024 798
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 } }
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization
Categories
Popular Posts
Horizon MUI Admin Dashboard Template
Nov 18, 2024
Elegent Material UI React Admin Dashboard Template
Nov 19, 2024
Dash UI HTML5 Admin Dashboard Template
Nov 18, 2024
Material Lite Admin Template
Nov 14, 2024