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
21namespace Poco {
22
23
24class TZInfo
25{
26public:
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__) || POCO_OS == POCO_OS_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
59private:
60 Poco::FastMutex _mutex;
61};
62
63
64static TZInfo tzInfo;
65
66
67int Timezone::utcOffset()
68{
69 return tzInfo.timeZone();
70}
71
72
73int 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
83bool 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
92std::string Timezone::name()
93{
94 return std::string(tzInfo.name(dst() != 0));
95}
96
97
98std::string Timezone::standardName()
99{
100 return std::string(tzInfo.name(false));
101}
102
103
104std::string Timezone::dstName()
105{
106 return std::string(tzInfo.name(true));
107}
108
109
110} // namespace Poco
111