How to get current date and time from internet in C#
By FoxLearn 11/9/2024 1:57:14 PM 69
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 } }
- How to capture image from webcam in C#
- How to pass anonymous types as parameters in C#
- How to search for files in folder in C#
- How to Search files in directory in C#
- How to get int value from enum in C#
- How to create a search box in C# WinForms
- How to get the color from a hexadecimal color code using .NET
- C# Tutorial
Categories
Popular Posts
Horizon MUI Admin Dashboard Template
11/18/2024
Plus Admin Dashboard Template
11/18/2024
Modular Admin Template
11/14/2024
Slim Material UI Admin Dashboard Template
11/15/2024
Freedash bootstrap lite
11/13/2024