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