Skip to content

Instantly share code, notes, and snippets.

@jongalloway
Forked from anonymous/timegetter.cs
Created September 26, 2015 23:04
Show Gist options
  • Save jongalloway/d5d946970205dfcdb6af to your computer and use it in GitHub Desktop.
Save jongalloway/d5d946970205dfcdb6af to your computer and use it in GitHub Desktop.
public class CurrentTimeGetter
{
private volatile Holder _holder;
const String rfc1123Pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";
public string GetCurrentTimeAsString()
{
DateTime now = DateTime.UtcNow;
Holder currentHolder = _holder;
if (currentHolder == null || Math.Abs(now.Ticks - currentHolder.TimeValue.Ticks) > TimeSpan.TicksPerSecond)
{
// value didn't exist or was out of date
currentHolder = new Holder()
{
TimeValue = now,
TimeValueAsString = now.ToString(rfc1123Pattern) // or whatever format
};
_holder = currentHolder;
}
return currentHolder.TimeValueAsString;
}
private sealed class Holder
{
internal DateTime TimeValue;
internal string TimeValueAsString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment