3 This file is part of libmspcore
4 Copyright © 2008-2009 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
14 #include <msp/core/systemerror.h>
15 #include <msp/strings/format.h>
16 #include "timestamp.h"
25 using Msp::Time::TimeZone;
28 long get_long(char *&ptr)
31 for(unsigned i=0; i<4; ++i)
32 result = (result<<8)+static_cast<unsigned char >(*ptr++);
37 TimeZone get_local_timezone()
40 TIME_ZONE_INFORMATION tzinfo;
41 DWORD dst = GetTimeZoneInformation(&tzinfo);
42 if(dst==TIME_ZONE_ID_INVALID)
43 throw Msp::system_error("GetTimeZoneInformation");
45 int offset = tzinfo.Bias;
46 if(dst==TIME_ZONE_ID_STANDARD)
47 offset += tzinfo.StandardBias;
48 else if(dst==TIME_ZONE_ID_DAYLIGHT)
49 offset += tzinfo.DaylightBias;
51 return TimeZone(offset);
53 int fd = open("/etc/localtime", O_RDONLY);
57 int len = read(fd, hdr, sizeof(hdr));
60 if(len==44 && hdr[0]=='T' && hdr[1]=='Z' && hdr[2]=='i' && hdr[3]=='f')
63 long isgmtcnt = get_long(ptr);
64 long isstdcnt = get_long(ptr);
65 long leapcnt = get_long(ptr);
66 long timecnt = get_long(ptr);
67 long typecnt = get_long(ptr);
68 long charcnt = get_long(ptr);
69 int size = timecnt*5+typecnt*6+isgmtcnt+isstdcnt+leapcnt*8+charcnt;
71 len = read(fd, buf, size);
76 time_t cur_time = Msp::Time::now().to_unixtime();
77 for(int i=0; i<timecnt; ++i)
78 if(get_long(ptr)<=cur_time)
86 for(int i=0; i<typecnt; ++i)
88 if((index>=0 && i==index) || (index<0 && !ptr[4] && gmtoff==-1))
90 gmtoff = get_long(ptr);
104 return TimeZone(gmtoff/60, name);
115 TimeZone::TimeZone():
119 TimeZone::TimeZone(int minutes):
124 int m = abs(minutes);
125 name = format("UTC%c%d", (minutes<0 ? '-' : '+'), m/60);
127 name += format(":%02d", m%60);
133 TimeZone::TimeZone(int minutes, const string &n):
138 const TimeZone &TimeZone::utc()
140 static TimeZone tz(0);
144 const TimeZone &TimeZone::local()
146 static TimeZone tz = get_local_timezone();