TimeExtensions.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace TEAMModelOS.SDK.Extension.SnowFlake
  5. {
  6. public static class TimeExtensions
  7. {
  8. public static Func<long> currentTimeFunc = InternalCurrentTimeMillis;
  9. public static long CurrentTimeMillis()
  10. {
  11. return currentTimeFunc();
  12. }
  13. public static IDisposable StubCurrentTime(Func<long> func)
  14. {
  15. currentTimeFunc = func;
  16. return new DisposableAction(() =>
  17. {
  18. currentTimeFunc = InternalCurrentTimeMillis;
  19. });
  20. }
  21. public static IDisposable StubCurrentTime(long millis)
  22. {
  23. currentTimeFunc = () => millis;
  24. return new DisposableAction(() =>
  25. {
  26. currentTimeFunc = InternalCurrentTimeMillis;
  27. });
  28. }
  29. private static readonly DateTime Jan1st1970 = new DateTime
  30. (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  31. private static long InternalCurrentTimeMillis()
  32. {
  33. return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
  34. }
  35. }
  36. }