Skip to content

Instantly share code, notes, and snippets.

@evgenyt1
Created November 25, 2012 18:09
Show Gist options
  • Save evgenyt1/4144607 to your computer and use it in GitHub Desktop.
Save evgenyt1/4144607 to your computer and use it in GitHub Desktop.
TimeService for .NET with ability to change Now/UtcNow/Today for testing purposes
using Microsoft.Win32;
using System;
namespace GarageTools
{
/// <summary>
/// Mocks DateTime Now/UtcNow/Today properties and allows setting them
/// (stores time shift in registry).
/// </summary>
/// <remarks>
/// IMPORTANT: Add read/write permissions to all users of your application to
/// HKEY_USERS\.DEFAULT\Software\TimeService.
/// </remarks>
public static class TimeService
{
#if DEBUG
private const string ValueKey = "MyApp1Shift";
private static readonly RegistryKey RegistryKey;
static TimeService()
{
// create this subkey manually and set permissions if it fails
RegistryKey = Registry.Users.CreateSubKey(".DEFAULT\\Software\\TimeService");
}
public static DateTime Now
{
get { return DateTime.Now + TimeShift; }
set { TimeShift = value - DateTime.Now; }
}
public static DateTime Today
{
get { return Now.Date; }
}
public static DateTime UtcNow
{
get { return DateTime.UtcNow + TimeShift; }
set { TimeShift = value - DateTime.UtcNow; }
}
public static TimeSpan TimeShift
{
get
{
var minutes = (string)RegistryKey.GetValue(ValueKey);
return minutes == null ? TimeSpan.Zero : TimeSpan.FromMinutes(double.Parse(minutes));
}
set { RegistryKey.SetValue(ValueKey, value.TotalMinutes); }
}
public static void Reset()
{
TimeShift = TimeSpan.Zero;
}
#else
public static DateTime Now
{
get { return DateTime.Now; }
}
public static DateTime Today
{
get { return DateTime.Today; }
}
public static DateTime UtcNow
{
get { return DateTime.UtcNow; }
}
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment