Skip to content

Instantly share code, notes, and snippets.

@nberardi
Created September 21, 2012 04:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nberardi/3759754 to your computer and use it in GitHub Desktop.
Save nberardi/3759754 to your computer and use it in GitHub Desktop.
A more precise DateTime in .NET
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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment