]> git.tdb.fi Git - libs/core.git/blobdiff - source/time/timezone.cpp
Add support for time zones
[libs/core.git] / source / time / timezone.cpp
diff --git a/source/time/timezone.cpp b/source/time/timezone.cpp
new file mode 100644 (file)
index 0000000..fd2487b
--- /dev/null
@@ -0,0 +1,80 @@
+/* $Id$
+
+This file is part of libmspcore
+Copyright © 2008  Mikko Rasa, Mikkosoft Productions
+Distributed under the LGPL
+*/
+
+#include <cstdlib>
+#include <sstream>
+#include <iomanip>
+#include <time.h>
+#include "timezone.h"
+#include "units.h"
+
+using namespace std;
+
+namespace {
+
+using Msp::Time::TimeZone;
+
+TimeZone get_local_timezone()
+{
+#ifdef WIN32
+       TIME_ZONE_INFORMATION tzinfo;
+       DWORD dst=GetTimeZoneInformation(&tzinfo);
+       if(dst==TIME_ZONE_ID_INVALID)
+               throw SystemError("Failed to get time zone information", GetLastError());
+
+       int offset=tzinfo.Bias;
+       if(dst==TIME_ZONE_ID_STANDARD)
+               offset+=tzinfo.StandardBias;
+       else if(dst==TIME_ZONE_ID_DAYLIGHT)
+               offset+=tzinfo.DaylightBias;
+
+       return TimeZone(offset);
+#else
+       tzset();
+       return TimeZone(timezone/60);
+#endif
+}
+
+}
+
+namespace Msp {
+namespace Time {
+
+TimeZone::TimeZone():
+       name("UTC")
+{ }
+
+TimeZone::TimeZone(int minutes_west):
+       offset(minutes_west*min)
+{
+       if(minutes_west)
+       {
+               ostringstream ss;
+               ss.fill('0');
+               int m=abs(minutes_west);
+               ss<<"UTC"<<(minutes_west<0 ? '-' : '+')<<m/60;
+               if(m%60)
+                       ss<<':'<<setw(2)<<m%60;
+       }
+       else
+               name="UTC";
+}
+
+const TimeZone &TimeZone::utc()
+{
+       static TimeZone tz(0);
+       return tz;
+}
+
+const TimeZone &TimeZone::local()
+{
+       static TimeZone tz=get_local_timezone();
+       return tz;
+}
+
+} // namespace Time
+} // namespace Msp