public
Created

A more precise DateTime in .NET

  • Download Gist
DateTimePrecise.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
using System;
using System.Diagnostics;
using System.Linq;
 
namespace System
{
public class DateTimePrecise
{
private static readonly DateTimePrecise Instance = new DateTimePrecise(10);
 
public static DateTime Now
{
get { return Instance.GetUtcNow().LocalDateTime; }
}
 
public static DateTime UtcNow
{
get { return Instance.GetUtcNow().UtcDateTime; }
}
 
public static DateTimeOffset NowOffset
{
get { return Instance.GetUtcNow().ToLocalTime(); }
}
 
public static DateTimeOffset UtcNowOffset
{
get { return Instance.GetUtcNow(); }
}
 
private const long TicksInOneSecond = 10000000L;
 
private readonly double _syncSeconds;
private readonly Stopwatch _stopwatch;
private DateTimeOffset _baseTime;
 
public DateTimePrecise(int syncSeconds)
{
_syncSeconds = syncSeconds;
_stopwatch = new Stopwatch();
 
Syncronize();
}
 
private void Syncronize()
{
lock (_stopwatch) {
_baseTime = DateTimeOffset.UtcNow;
_stopwatch.Restart();
}
}
 
public DateTimeOffset GetUtcNow()
{
var elapsedSeconds = _stopwatch.ElapsedTicks / (double)Stopwatch.Frequency;
if (elapsedSeconds > _syncSeconds) {
Syncronize();
 
// account for any time that has passed since the stopwatch was syncronized
elapsedSeconds = _stopwatch.ElapsedTicks / (double)Stopwatch.Frequency;
}
 
var elapsedTicks = Convert.ToInt64(elapsedSeconds * TicksInOneSecond);
return _baseTime.AddTicks(elapsedTicks);
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.