Getting date from a C#website

Asked

Viewed 34 times

1

I am developing a program in C# that allows a click at a certain time chosen by the user. For now the program clicks subtracting the time chosen by the user with the local time, but I discovered a little while ago that through the Headers of a website you can know the exact time of the server, which would make it easier for me because the program is being developed to work based on the time of the same.

I use these lines of code to get the Headers of the website:

var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.exemplo.com.pt/");
var response = myHttpWebRequest.GetResponse();

To subtract the time entered by the user and the local time I use this line of code:

TimeSpan wait_time = objetivo.Subtract(DateTime.Now); //'objetivo' = hora inserida pelo utilizador

My question is, how can I just pick up the date at Headers from the website and then subtract from the time chosen by the user?

1 answer

0


The object response that you use is of the type HttpResponse. He owns a property called Headers, a collection of values through which it should be possible to read page headers.

Something like:

string dataCabecalho = response.Headers.Get("Date");

Note that the method Get headers, for the header Date, returns a text. This text should still be transformed into a date, something like:

DateTime dataRealServidor;
DateTime.TryParse(dataCabecalho, CultureInfo.InvariantCulture.DateTimeFormat, 
DateTimeStyles.None, out dataRealServidor);
  • Thank you so much Renan! It really worked returning something like 19-04-2017 15:30:35. Is there any way to know the Milliseconds either, or the Header Date only returns Hours, Minutes and Seconds?

  • 1

    Unfortunately, as far as I know, that header only goes up to the second.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.