Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Fix inaccurate CurrentServerTime #253

Merged
merged 1 commit into from
Aug 17, 2020
Merged

Fix inaccurate CurrentServerTime #253

merged 1 commit into from
Aug 17, 2020

Conversation

TheDruidsKeeper
Copy link
Contributor

The Stopwatch.ElapsedTicks property is timer ticks, which is not the same as the DateTime.Ticks according to the note in the remarks section of the documentation (and my testing that led to this discovery).

Try the following simple c# sample to see the difference:

var serverTimeAtStart = DateTime.UtcNow;
var startedAt = Stopwatch.StartNew();
Thread.Sleep(5000);
var CurrentServerTime = new DateTime(serverTimeAtStart.Ticks + startedAt.ElapsedTicks, DateTimeKind.Utc);
var CorrectServerTime = new DateTime(serverTimeAtStart.Ticks + startedAt.Elapsed.Ticks, DateTimeKind.Utc);
Debug.WriteLine($"Current: {CurrentServerTime}\r\nCorrect: {CorrectServerTime}\r\nNow: {DateTime.UtcNow}");

The `Stopwatch.ElapsedTicks` property is _timer_ ticks, which is not the same as the `DateTime.Ticks` according to the note in the remarks section of [the documentation](https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch.elapsedticks?view=netcore-3.1#remarks) (and my testing that led to this discovery).

Try the following simple c# sample to see the difference:
```
var serverTimeAtStart = DateTime.UtcNow;
var startedAt = Stopwatch.StartNew();
Thread.Sleep(5000);
var CurrentServerTime = new DateTime(serverTimeAtStart.Ticks + startedAt.ElapsedTicks, DateTimeKind.Utc);
var CorrectServerTime = new DateTime(serverTimeAtStart.Ticks + startedAt.Elapsed.Ticks, DateTimeKind.Utc);
Debug.WriteLine($"Current: {CurrentServerTime}\r\nCorrect: {CorrectServerTime}\r\nNow: {DateTime.UtcNow}");
```
@mythz mythz merged commit 82fd1fb into ServiceStack:master Aug 17, 2020
@mythz
Copy link
Member

mythz commented Aug 17, 2020

Nice catch, thx 👍

@TheDruidsKeeper TheDruidsKeeper deleted the patch-1 branch August 17, 2020 22:46
@mythz
Copy link
Member

mythz commented Aug 17, 2020

FYI this is now available from the latest v5.9.3 that's now available on MyGet.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants