00001 // $Id: Tm.h,v 1.4 2010/09/30 14:16:42 organtin Exp $ 00002 00003 #ifndef TM_HH 00004 #define TM_HH 00005 00006 #include <stdexcept> 00007 #include <string> 00008 #include <iostream> 00009 #include <time.h> 00010 #include <stdint.h> 00011 #include <limits.h> 00012 00013 // Wrapper class for time.h tm struct 00014 class Tm { 00015 static const uint64_t NEG_INF_MICROS = 0; 00016 // GO: maximum UNIX time 00017 static const uint64_t PLUS_INF_MICROS = (uint64_t)INT_MAX * 1000000; 00018 00019 public: 00020 // Default constructor makes a null Tm 00021 Tm(); 00022 00023 // Initialized constructor 00024 Tm(struct tm * initTm); 00025 00026 Tm(uint64_t micros); 00027 00028 // Destructor 00029 virtual ~Tm(); 00030 00031 /* 00032 * Return a pointer to the tm data structure. 00033 */ 00034 struct tm c_tm() const; 00035 00036 /* 00037 * Returns true if this Tm is null 00038 */ 00039 int isNull() const; 00040 00041 /* 00042 * Sets this Tm to null 00043 */ 00044 void setNull(); 00045 00046 00047 static Tm plusInfinity() 00048 { 00049 return Tm(PLUS_INF_MICROS); 00050 }; 00051 00052 00053 static Tm negInfinity() 00054 { 00055 return Tm(NEG_INF_MICROS); 00056 }; 00057 00058 /* 00059 * String representation of Tm in YYYY-MM-DD hh:mm:ss format 00060 */ 00061 std::string str() const; 00062 00063 /* 00064 * return number of microseconds since Jan 1 1970 00065 */ 00066 uint64_t microsTime() const; 00067 00068 /* 00069 * Set self to current time 00070 */ 00071 void setToCurrentLocalTime(); 00072 void setToCurrentGMTime(); 00073 00074 /* 00075 * Set using time_t 00076 */ 00077 void setToLocalTime( time_t t); 00078 void setToGMTime( time_t t ); 00079 00080 /* 00081 * Set using microseconds 00082 */ 00083 void setToMicrosTime(uint64_t micros); 00084 00085 /* 00086 * Set to string of format YYYY-MM-DD HH:MM:SS 00087 */ 00088 void setToString(const std::string s) throw(std::runtime_error); 00089 00090 void dumpTm(); 00091 00092 inline bool operator==(const Tm &t) const 00093 { return (m_tm.tm_hour == t.m_tm.tm_hour && 00094 m_tm.tm_isdst == t.m_tm.tm_isdst && 00095 m_tm.tm_mday == t.m_tm.tm_mday && 00096 m_tm.tm_min == t.m_tm.tm_min && 00097 m_tm.tm_mon == t.m_tm.tm_mon && 00098 m_tm.tm_sec == t.m_tm.tm_sec && 00099 m_tm.tm_wday == t.m_tm.tm_wday && 00100 m_tm.tm_yday == t.m_tm.tm_yday && 00101 m_tm.tm_year == t.m_tm.tm_year); 00102 } 00103 00104 inline bool operator!=(const Tm &t) const { return !(t == *this); } 00105 00106 Tm& operator-=(int seconds) { 00107 setToMicrosTime(microsTime() - seconds * 1e6); 00108 return *this; 00109 } 00110 Tm& operator+=(int seconds) { 00111 setToMicrosTime(microsTime() + seconds * 1e6); 00112 return *this; 00113 } 00114 00115 private: 00116 struct tm m_tm; 00117 }; 00118 00119 #endif