DateTimeUtilities.cs 1.6 KB

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