DateTimeUtilities.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. namespace Org.BouncyCastle.Utilities.Date
  4. {
  5. public class DateTimeUtilities
  6. {
  7. public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1);
  8. private DateTimeUtilities()
  9. {
  10. }
  11. /// <summary>
  12. /// Return the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC) for a given DateTime value.
  13. /// </summary>
  14. /// <param name="dateTime">A UTC DateTime value not before epoch.</param>
  15. /// <returns>Number of whole milliseconds after epoch.</returns>
  16. /// <exception cref="ArgumentException">'dateTime' is before epoch.</exception>
  17. public static long DateTimeToUnixMs(
  18. DateTime dateTime)
  19. {
  20. if (dateTime.CompareTo(UnixEpoch) < 0)
  21. throw new ArgumentException("DateTime value may not be before the epoch", "dateTime");
  22. return (dateTime.Ticks - UnixEpoch.Ticks) / TimeSpan.TicksPerMillisecond;
  23. }
  24. /// <summary>
  25. /// Create a DateTime value from the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
  26. /// </summary>
  27. /// <param name="unixMs">Number of milliseconds since the epoch.</param>
  28. /// <returns>A UTC DateTime value</returns>
  29. public static DateTime UnixMsToDateTime(
  30. long unixMs)
  31. {
  32. return new DateTime(unixMs * TimeSpan.TicksPerMillisecond + UnixEpoch.Ticks);
  33. }
  34. /// <summary>
  35. /// Return the current number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
  36. /// </summary>
  37. public static long CurrentUnixMs()
  38. {
  39. return DateTimeToUnixMs(DateTime.UtcNow);
  40. }
  41. }
  42. }
  43. #endif