Smccullough
Smccullough

Reputation: 363

How do I request server time using ASP.Net/ C#

I'm creating a countdown timer for a project I'm on and I feel its important to get the most accurate time possible. What is more accurate and, more importantly, the most unalterable than server time?

The project requires days/hours/minutes/seconds so if I could grab the exact time the page was requested from the server I could then just throw it in a JavaScript variable and work it out from there.

Upvotes: 1

Views: 4875

Answers (3)

Ben
Ben

Reputation: 546

Why don't you query a NIST time server? You must consider which stratum your server is on before you assume that the server is a better source than the client. Also consider that you are posting back to a web server, not the DC, which is more often the reference time source for a network. Lastly, if you do not have an authoritative time source to query, consider allowing the user to put in a time hack, or a manual input that would be the difference between your time and the authoritative time.

How to Query an NTP Server

A jQuery countdown clock that I have had success with.

Upvotes: 0

Diego
Diego

Reputation: 16714

One way would be to get the timespan of the difference between the objetive time and current time and then total seconds:

TimeSpan diff = objetiveDateTime - DateTime.Now;
int totalSeconds = diff.TotalSeconds();

Some other way would be to get the objetive date and save it in a js variable in some format js understands (e.g. "October 13, 1975 11:13:00") and then create Date object in js.

Upvotes: 0

Brad
Brad

Reputation: 15577

Since this is run on the server, it gives you the server time.

DateTime currentTime = DateTime.Now;

This you can put in a hidden field on the page and read it with JS when the page loads.

Then, you'll either

  • need to also know the client time the page loaded so you can calculate how much time has elapsed

    OR

  • have JS increment a counter value that you add to the server time.

With either of these, of course, you're using setTimeout to kick off some JS function.


However, don't forget about time zones!!! Is this important?

Upvotes: 6

Related Questions