CppCommon 1.0.5.0
C++ Common Library
Loading...
Searching...
No Matches
timezone.cpp
Go to the documentation of this file.
1
9#include "time/timezone.h"
10
11#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
12#include <time.h>
13#elif defined(_WIN32) || defined(_WIN64)
14#include <windows.h>
15#endif
16
17namespace CppCommon {
18
19Timezone::Timezone() : _name(), _offset(Timespan::zero()), _dstoffset(Timespan::zero())
20{
21#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
22 struct tm local;
23 time_t seconds = time(nullptr);
24 if (localtime_r(&seconds, &local) != &local)
25 throwex SystemException("Cannot convert current time to local date & time structure!");
26 _name = local.tm_zone;
27 if (local.tm_isdst > 0)
28 {
29 _offset = Timespan::seconds(local.tm_gmtoff - 3600);
31 }
32 else
33 {
34 _offset = Timespan::seconds(local.tm_gmtoff);
36 }
37#elif defined(_WIN32) || defined(_WIN64)
38 WCHAR* name;
39 char buffer[1024];
40 DYNAMIC_TIME_ZONE_INFORMATION dtzi;
41 DWORD result = GetDynamicTimeZoneInformation(&dtzi);
42 switch (result)
43 {
44 case TIME_ZONE_ID_UNKNOWN:
45 name = dtzi.TimeZoneKeyName;
46 _offset = -Timespan::minutes(dtzi.Bias);
48 break;
49 case TIME_ZONE_ID_STANDARD:
50 name = dtzi.StandardName;
51 _offset = -Timespan::minutes(dtzi.Bias);
53 break;
54 case TIME_ZONE_ID_DAYLIGHT:
55 name = dtzi.DaylightName;
56 _offset = -Timespan::minutes(dtzi.Bias);
57 _dstoffset = -Timespan::minutes(dtzi.DaylightBias);
58 break;
59 default:
60 throwex SystemException("Cannot get dynamic timezone informaction!");
61 }
62 // Convert timezone name to UTF-8 encoding.
63 if (!WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, name, -1, buffer, 1024, nullptr, nullptr))
64 throwex SystemException("Cannot get dynamic timezone key name!");
65 _name = buffer;
66#endif
67}
68
69} // namespace CppCommon
System exception.
Definition exceptions.h:107
int64_t seconds() const noexcept
Get total seconds of the current timespan.
Definition timespan.h:138
int64_t minutes() const noexcept
Get total minutes of the current timespan.
Definition timespan.h:135
static Timespan zero() noexcept
Get zero timespan.
Definition timespan.h:182
Timespan _dstoffset
Timezone daylight saving time offset.
Definition timezone.h:112
std::string _name
Timezone name.
Definition timezone.h:108
static Timezone local()
Get the local timezone.
Definition timezone.h:99
Timezone()
Initialize timezone with a current local timezone.
Definition timezone.cpp:19
Timespan _offset
Timezone offset.
Definition timezone.h:110
const std::string & name() const noexcept
Get timezone name.
Definition timezone.h:60
#define throwex
Throw extended exception macro.
Definition exceptions.h:23
C++ Common project definitions.
Time definition.
Timezone definition.