SHARE
TWEET

Untitled

a guest Aug 13th, 2017 50 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2.  
  3. class SystemTime
  4. {
  5.     private static Func<DateTime> _defaultTimeSource = () => DateTime.UtcNow;
  6.     private static Func<DateTime> _timeSource = _defaultTimeSource;
  7.     public static DateTime UtcNow => _timeSource();
  8.  
  9.     public static IDisposable Freeze(DateTime? time = null)
  10.     {
  11.         var frozen = time ?? DateTime.UtcNow;
  12.         _timeSource = () => frozen;
  13.         return Resetter.Instace;
  14.     }
  15.  
  16.     private static void Reset() => _timeSource = _defaultTimeSource;
  17.  
  18.     private class Resetter : IDisposable
  19.     {
  20.         public static readonly Resetter Instace = new Resetter();
  21.        
  22.         public void Dispose()
  23.         {
  24.             SystemTime.Reset();
  25.         }
  26.     }
  27. }
  28.  
  29. class Program
  30. {
  31.     static void Main(string[] args)
  32.     {
  33.         using (SystemTime.Freeze(new DateTime(2015, 10, 2)))
  34.         {
  35.             Console.WriteLine(SystemTime.UtcNow);
  36.         }
  37.        
  38.         Console.WriteLine(SystemTime.UtcNow);
  39.     }
  40. }
RAW Paste Data
Top