Skip to content

Instantly share code, notes, and snippets.

@DaveHogan
Last active December 22, 2015 00:39
Show Gist options
  • Select an option

  • Save DaveHogan/6390722 to your computer and use it in GitHub Desktop.

Select an option

Save DaveHogan/6390722 to your computer and use it in GitHub Desktop.
Replacing DateTime.Now method to assist with time sensitive unit tests
// Following on from: http://stackoverflow.com/q/7661953/235644
//
// Observations:
// Should consider using UTC for better globalization support
//
// Usage:
DateTimeExtensions.SetNowFunction(() => date1);
/// <summary>
/// Allow custom generation of Now times.
/// </summary>
private static Func<DateTime> _nowFunction = () => DateTime.Now;
/// <summary>
/// Get the current time using the Now generator function
/// </summary>
public static DateTime Now
{
get { return _nowFunction(); }
}
/// <summary>
/// Set the Now generator function
/// </summary>
public static void SetNowFunction(Func<DateTime> function)
{
_nowFunction = function;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment