How to get current date and time from internet in C#
By FoxLearn 11/9/2024 1:57:14 PM 93
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 get application folder path in C#
- How to copy data to clipboard in C#
- How to mark a method as obsolete or deprecated in C#
- How to Call the Base Constructor in C#
- Deep Copy of Object in C#
- How to Catch Multiple Exceptions in C#
- How to cast int to enum in C#
- What is the difference between String and string in C#?
Categories
Popular Posts
SB Admin Template
11/17/2024
RuangAdmin Template
11/17/2024
DASHMIN Admin Dashboard Template
11/17/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024