2 Copyright (C) 2014 Carl Hetherington <cth@carlh.net>
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 #include "local_time.h"
21 #include "exceptions.h"
22 #include <boost/lexical_cast.hpp>
26 using boost::lexical_cast;
29 LocalTime::LocalTime ()
31 time_t now = time (0);
32 struct tm* tm = localtime (&now);
33 _year = tm->tm_year + 1900;
34 _month = tm->tm_mon + 1;
35 _day = tm->tm_mday + 1;
43 offset = tm->tm_gmtoff / 60;
45 TIME_ZONE_INFORMATION tz;
46 GetTimeZoneInformation (&tz);
50 bool const negative = offset < 0;
51 offset = negative ? -offset : offset;
53 _tz_hour = offset / 60;
54 _tz_minute = offset % 60;
61 /** @param s A string of the form 2013-01-05T18:06:59+04:00 */
62 LocalTime::LocalTime (string s)
64 /* 2013-01-05T18:06:59+04:00 */
65 /* 0123456789012345678901234 */
67 if (s.length() < 25) {
68 throw TimeFormatError (s);
71 /* Check incidental characters */
72 if (s[4] != '-' || s[7] != '-' || s[10] != 'T' || s[13] != ':' || s[16] != ':' || s[22] != ':') {
73 throw TimeFormatError (s);
76 _year = lexical_cast<int> (s.substr (0, 4));
77 _month = lexical_cast<int> (s.substr (5, 2));
78 _day = lexical_cast<int> (s.substr (8, 2));
79 _hour = lexical_cast<int> (s.substr (11, 2));
80 _minute = lexical_cast<int> (s.substr (14, 2));
81 _second = lexical_cast<int> (s.substr (17, 2));
82 _tz_hour = lexical_cast<int> (s.substr (20, 2));
83 _tz_minute = lexical_cast<int> (s.substr (23, 2));
87 } else if (s[19] != '+') {
88 throw TimeFormatError (s);
93 LocalTime::as_string () const
97 buffer, sizeof (buffer),
98 "%04d-%02d-%02dT%02d:%02d:%02d%s%02d:%02d",
99 _year, _month, _day, _hour, _minute, _second, (_tz_hour >= 0 ? "+" : "-"), abs (_tz_hour), _tz_minute