pkixtime.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. */
  6. #include "pkix/Time.h"
  7. #include "pkix/pkixutil.h"
  8. #ifdef _WINDOWS
  9. #ifdef _MSC_VER
  10. #pragma warning(push, 3)
  11. #endif
  12. #include "windows.h"
  13. #ifdef _MSC_VER
  14. #pragma warning(pop)
  15. #endif
  16. #else
  17. #include "sys/time.h"
  18. #endif
  19. namespace mozilla { namespace pkix {
  20. Time
  21. Now()
  22. {
  23. uint64_t seconds;
  24. #ifdef _WINDOWS
  25. // "Contains a 64-bit value representing the number of 100-nanosecond
  26. // intervals since January 1, 1601 (UTC)."
  27. // - http://msdn.microsoft.com/en-us/library/windows/desktop/ms724284(v=vs.85).aspx
  28. FILETIME ft;
  29. GetSystemTimeAsFileTime(&ft);
  30. uint64_t ft64 = (static_cast<uint64_t>(ft.dwHighDateTime) << 32) |
  31. ft.dwLowDateTime;
  32. seconds = (DaysBeforeYear(1601) * Time::ONE_DAY_IN_SECONDS) +
  33. ft64 / (1000u * 1000u * 1000u / 100u);
  34. #else
  35. // "The gettimeofday() function shall obtain the current time, expressed as
  36. // seconds and microseconds since the Epoch."
  37. // - http://pubs.opengroup.org/onlinepubs/009695399/functions/gettimeofday.html
  38. timeval tv;
  39. (void) gettimeofday(&tv, nullptr);
  40. seconds = (DaysBeforeYear(1970) * Time::ONE_DAY_IN_SECONDS) +
  41. static_cast<uint64_t>(tv.tv_sec);
  42. #endif
  43. return TimeFromElapsedSecondsAD(seconds);
  44. }
  45. Time
  46. TimeFromEpochInSeconds(uint64_t secondsSinceEpoch)
  47. {
  48. uint64_t seconds = (DaysBeforeYear(1970) * Time::ONE_DAY_IN_SECONDS) +
  49. secondsSinceEpoch;
  50. return TimeFromElapsedSecondsAD(seconds);
  51. }
  52. } } // namespace mozilla::pkix