libanna.time refactoring
[anna.git] / source / time / Date.cpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #include <anna/core/tracing/Logger.hpp>
38 #include <anna/core/tracing/TraceWriter.hpp>
39 #include <anna/config/defines.hpp>
40 #include <anna/core/functions.hpp>
41 #include <anna/core/mt/Guard.hpp>
42 #include <anna/xml/xml.hpp>
43
44 // Local
45 #include <anna/time/Date.hpp>
46 #include <anna/time/functions.hpp>
47 #include <anna/time/internal/sccs.hpp>
48
49 // Standard
50 #include <stdlib.h> // putenv
51 #include <iostream>
52
53
54 using namespace anna;
55 using namespace anna::time;
56
57
58
59 //******************************************************************************
60 //------------------------------------------------------------------------- Date
61 //******************************************************************************
62
63 // private:
64
65 //------------------------------------------------------------------------------
66 //----------------------------------------------------------- Date::initialize()
67 //------------------------------------------------------------------------------
68 void Date::initialize(const char * TZ) throw() {
69   a_timestamp = ::time(NULL);
70   setTz(TZ);
71 }
72
73
74 //------------------------------------------------------------------------------
75 //-------------------------------------------------------------- Date::refresh()
76 //------------------------------------------------------------------------------
77 void Date::refresh(void) throw() {
78   anna::Guard guard(a_mutex);
79
80   // Set current/programmed timezone
81   a_tz.apply();
82
83   // Rescue info:
84   struct tm *ptrTm = localtime(&a_timestamp);
85   a_tm = *ptrTm;
86 }
87
88
89
90 // public:
91
92 //------------------------------------------------------------------------------
93 //----------------------------------------------------------------- Date::Date()
94 //------------------------------------------------------------------------------
95 Date::Date(const char *TZ) {
96   time::sccs::activate();
97
98   if(!functions::initialized()) {
99     std::cerr << std::endl << "Develop ERROR: you should firstly invoke anna::time::functions::initialize() before using time module" << std::endl;
100   }
101
102   initialize(TZ);
103 };
104
105
106 //------------------------------------------------------------------------------
107 //---------------------------------------------------------------- Date::setTz()
108 //------------------------------------------------------------------------------
109 void Date::setTz(const char * TZ) throw() {
110   if (TZ) a_tz.set(TZ);
111   else a_tz = functions::getSystemTimezone(); 
112
113   refresh();
114 }
115
116
117 //------------------------------------------------------------------------------
118 //---------------------------------------------------- Date::setSystemTimezone()
119 //------------------------------------------------------------------------------
120 void Date::setSystemTimezone() throw() {
121   a_tz = functions::getSystemTimezone();
122   // Refresh the other data:
123   refresh();
124 }
125
126
127 //------------------------------------------------------------------------------
128 //---------------------------------------------------------------- Date::store()
129 //------------------------------------------------------------------------------
130 void Date::store(const time_t & unixTimestamp) throw() {
131   a_timestamp = unixTimestamp;
132   // Refresh the other data:
133   refresh();
134 }
135
136
137 //------------------------------------------------------------------------------
138 //------------------------------------------------------------- Date::storeNtp()
139 //------------------------------------------------------------------------------
140 void Date::storeNtp(const unsigned int & ntpTimestamp) throw() {
141   a_timestamp = ntpTimestamp - TIMESTAMP_OFFSET_NTP1900_OVER_UNIX1970;
142   // Refresh the other data:
143   refresh();
144 }
145
146
147 //------------------------------------------------------------------------------
148 //---------------------------------------------------------------- Date::store()
149 //------------------------------------------------------------------------------
150 void Date::store(const struct tm &date, const char *TZ)
151
152 throw(anna::RuntimeException)
153
154 {
155   if (TZ) {
156     Timezone aux;
157     aux.set(TZ);
158     aux.apply();
159   }
160   else {
161     functions::getSystemTimezone().apply();
162   }
163
164   // Set '-1' on 'tm_isdst', or it could be an ambiguity on tranformation
165   //  returning inexact timestamp. This setting force system to check the correct flag:
166   struct tm dateIsdst_1 = date;
167   dateIsdst_1.tm_isdst = -1;
168   time_t unixTimestamp = mktime((struct tm*) & dateIsdst_1);
169
170   if(unixTimestamp == (time_t) - 1)
171     throw anna::RuntimeException("Error during mktime() conversion !!", ANNA_FILE_LOCATION);
172
173   a_timestamp = unixTimestamp;
174
175   // Refresh the othr data:
176   refresh();
177 }
178
179
180 //------------------------------------------------------------------------------
181 //---------------------------------------------------------------- Date::store()
182 //------------------------------------------------------------------------------
183 void Date::store(const std::string &stringDate, const char *TZ, const char *strptimeFormat)
184 throw(anna::RuntimeException)
185 {
186   if(strptimeFormat == NULL)
187     throw anna::RuntimeException("Invalid NULL strptimeFormat !!", ANNA_FILE_LOCATION);
188
189   // Get equivalent 'tm':
190   struct tm tmOrigin;
191   memset(&tmOrigin, 0, sizeof(tmOrigin));
192
193   if(strptime(stringDate.c_str(), strptimeFormat, &tmOrigin) == NULL) {
194     std::string msg("Error during strptime() conversion: '");
195     msg += stringDate;
196     msg += "' can't be interpreted as '";
197     msg += strptimeFormat;
198     msg += "'";
199     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
200   }
201
202   store(tmOrigin, TZ);
203 }
204
205
206 //------------------------------------------------------------------------------
207 //-------------------------------------------------------------- Date::operator=
208 //------------------------------------------------------------------------------
209 Date & Date::operator = (const Date & d) {
210   // avoid itself copy: i.e., Date a,b; a=&b; a=b; b=a;
211   if(this == &d) return (*this);
212
213   a_timestamp = d.getUnixTimestamp();
214   a_tz.set(d.getTz());
215   a_tm = d.getTm();
216   return (*this);
217 }
218
219
220 // gets
221
222
223 //------------------------------------------------------------------------------
224 //--------------------------------------------------------------- Date::getDay()
225 //------------------------------------------------------------------------------
226 const char *Date::getDay(void) const throw() {
227
228   static const char *weekdayname[] = {"Sunday", "Monday", "Tuesday",
229     "Wednesday", "Thursday", "Friday", "Saturday"};
230
231   return weekdayname[a_tm.tm_wday];
232 }
233
234
235 //------------------------------------------------------------------------------
236 //------------------------------------------------------- Date::yyyymmddHHmmss()
237 //------------------------------------------------------------------------------
238 std::string Date::yyyymmddHHmmss(void) const throw() {
239   return anna::functions::asString("%04d%02d%02d%02d%02d%02d",
240      1900 + a_tm.tm_year, 1 + (a_tm.tm_mon), a_tm.tm_mday,
241      a_tm.tm_hour, a_tm.tm_min, a_tm.tm_sec);
242 }
243
244
245 //------------------------------------------------------------------------------
246 //------------------------------------------------------------- Date::asString()
247 //------------------------------------------------------------------------------
248 std::string Date::asString(void) const throw() {
249
250   std::string result = anna::functions::asString("%s %02d/%02d/%04d %02d:%02d:%02d ", getDay(),
251                           getTm().tm_mday, 1 + (getTm().tm_mon), 1900 + getTm().tm_year,
252                           getTm().tm_hour, getTm().tm_min, getTm().tm_sec);
253   result += getTzAsString();
254   result += anna::functions::asString(", isdst = %d [Unix Timestamp: %ld, Ntp Timestamp: %u]", getTm().tm_isdst, getUnixTimestamp(), getNtpTimestamp());
255   result += ", System Timezone: ";
256   result += functions::getSystemTimezone().asString();
257
258   return result;
259 }
260
261
262 //------------------------------------------------------------------------------
263 //---------------------------------------------------------------- Date::asXML()
264 //------------------------------------------------------------------------------
265 anna::xml::Node* Date::asXML(anna::xml::Node* parent) const throw() {
266   //anna::xml::Node* result = parent->createChild("anna.time.Date");
267   parent->createAttribute("Date", anna::functions::asString("%02d/%02d/%04d", getTm().tm_mday, 1 + (getTm().tm_mon), 1900 + getTm().tm_year));
268   parent->createAttribute("Day", getDay());
269   parent->createAttribute("Time", anna::functions::asString("%02d:%02d:%02d", getTm().tm_hour, getTm().tm_min, getTm().tm_sec));
270   parent->createAttribute("TZ", getTzAsString());
271   parent->createAttribute("Isdst", (getTm().tm_isdst) ? "yes" : "no");
272   parent->createAttribute("UnixTimestamp", anna::functions::asString((const int)getUnixTimestamp()));
273   parent->createAttribute("NtpTimestamp", anna::functions::asString(getNtpTimestamp()));
274   parent->createAttribute("SystemTimezone", functions::getSystemTimezone().asString());
275
276   return parent;
277 }
278