Timezone_UNIX.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. //
  2. // Timezone_UNIX.cpp
  3. //
  4. // $Id: //poco/1.4/Foundation/src/Timezone_UNIX.cpp#2 $
  5. //
  6. // Library: Foundation
  7. // Package: DateTime
  8. // Module: Timezone
  9. //
  10. // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
  11. // and Contributors.
  12. //
  13. // SPDX-License-Identifier: BSL-1.0
  14. //
  15. #include "Poco/Timezone.h"
  16. #include "Poco/Exception.h"
  17. #include "Poco/Mutex.h"
  18. #include <ctime>
  19. namespace Poco {
  20. class TZInfo
  21. {
  22. public:
  23. TZInfo()
  24. {
  25. tzset();
  26. }
  27. int timeZone()
  28. {
  29. Poco::FastMutex::ScopedLock lock(_mutex);
  30. #if defined(__APPLE__) || defined(__FreeBSD__) || defined (__OpenBSD__) || defined(POCO_ANDROID) // no timezone global var
  31. std::time_t now = std::time(NULL);
  32. struct std::tm t;
  33. gmtime_r(&now, &t);
  34. std::time_t utc = std::mktime(&t);
  35. return now - utc;
  36. #elif defined(__CYGWIN__)
  37. tzset();
  38. return -_timezone;
  39. #else
  40. tzset();
  41. return -timezone;
  42. #endif
  43. }
  44. const char* name(bool dst)
  45. {
  46. Poco::FastMutex::ScopedLock lock(_mutex);
  47. tzset();
  48. return tzname[dst ? 1 : 0];
  49. }
  50. private:
  51. Poco::FastMutex _mutex;
  52. };
  53. static TZInfo tzInfo;
  54. int Timezone::utcOffset()
  55. {
  56. return tzInfo.timeZone();
  57. }
  58. int Timezone::dst()
  59. {
  60. std::time_t now = std::time(NULL);
  61. struct std::tm t;
  62. if (!localtime_r(&now, &t))
  63. throw Poco::SystemException("cannot get local time DST offset");
  64. return t.tm_isdst == 1 ? 3600 : 0;
  65. }
  66. bool Timezone::isDst(const Timestamp& timestamp)
  67. {
  68. std::time_t time = timestamp.epochTime();
  69. struct std::tm* tms = std::localtime(&time);
  70. if (!tms) throw Poco::SystemException("cannot get local time DST flag");
  71. return tms->tm_isdst > 0;
  72. }
  73. std::string Timezone::name()
  74. {
  75. return std::string(tzInfo.name(dst() != 0));
  76. }
  77. std::string Timezone::standardName()
  78. {
  79. return std::string(tzInfo.name(false));
  80. }
  81. std::string Timezone::dstName()
  82. {
  83. return std::string(tzInfo.name(true));
  84. }
  85. } // namespace Poco