Reputation: 323
I need to simulate a clock that is fairly precise. I need some kind of DateTime.Now, not for the local time, but for a web server's time(which can differ a few seconds from system time).
The thing is I need to be accurate, even 3 seconds is way too much difference. Any way to create a DateTime object and then "let it run" so it shows the current server time?
PS: Not talking about a time server, but a normal web server. Can I avoid setting the system time to server time?
Upvotes: 0
Views: 1154
Reputation: 323
So this is what I have come up with:
public class ServerTime
{
public static DateTime Now
{
get
{
if (baseTime != null)
return baseTime.Add(swatch.Elapsed);
else
return DateTime.Now;
}
set
{
baseTime = value;
swatch.Reset();
swatch.Start();
}
}
private static DateTime baseTime;
private static Stopwatch swatch = new Stopwatch();
}
Not really sure how to handle ServerTime.Now if the baseTime was not set yet. I would probably never call this property before it was set, but as always: Don't trust your own code.
Upvotes: 0
Reputation: 354356
DateTime.Now
is not very accurate, especially not for measuring time differences. »Letting it run« suggests that you actually want to use a Stopwatch and a separate DateTime
as starting time. You can then generate a current timestamp by just adding your start time and the elapsed time of the Stopwatch
.
Upvotes: 2