Advertisement
Guest User

Untitled

a guest
Dec 17th, 2018
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.13 KB | None | 0 0
  1.   public static class DateProvider
  2.     {
  3.         private static DateTime? _frozenTime;
  4.  
  5.         public static DateTime Now
  6.         {
  7.             get { return _frozenTime ?? DateTime.Now; }
  8.         }
  9.  
  10.         public static DateTime NowTruncated
  11.         {
  12.             get
  13.             {
  14.                 return _frozenTime.HasValue
  15.                            ? new DateTime(_frozenTime.Value.Year, frozenTime.Value.Month, frozenTime.Value.Day,
  16.                                           frozenTime.Value.Hour, frozenTime.Value.Minute, _frozenTime.Value.Second)
  17.                            : DateTime.Now;
  18.             }
  19.         }
  20.  
  21.         public static DateTime Today
  22.         {
  23.             get { return Now.Date; }
  24.         }
  25.  
  26.         public static IDisposable FreezeTime(DateTime theFrozenTime)
  27.         {
  28.             _frozenTime = theFrozenTime;
  29.             return new DisposableAction(() => _frozenTime = null);
  30.         }
  31.  
  32.         public static bool IsFrozen()
  33.         {
  34.             return _frozenTime.HasValue;
  35.         }
  36.  
  37.         public static void UnFreezeTime()
  38.         {
  39.             _frozenTime = null;
  40.         }
  41.     }
  42. /// <summary>
  43.     /// Better sytnax for context operation.
  44.     /// Wraps a delegate that is executed when the Dispose method is called.
  45.     /// This allows to do context sensitive things easily.
  46.     /// Basically, it mimics Java's anonymous classes.
  47.     /// </summary>
  48.     public class DisposableAction : IDisposable
  49.     {
  50.         readonly Proc action;
  51.  
  52.         /// <summary>
  53.         /// Initializes a new instance of the <see cref="DisposableAction"/> class.
  54.         /// </summary>
  55.         /// <param name="action">The action to execute on dispose</param>
  56.         public DisposableAction(Proc action)
  57.         {
  58.             if (action == null)
  59.                 throw new ArgumentNullException("action");
  60.             this.action = action;
  61.         }
  62.  
  63.         /// <summary>
  64.         /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  65.         /// </summary>
  66.         public virtual void Dispose()
  67.         {
  68.             action();
  69.         }
  70.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement