首页 > 代码库 > C++学习之路: 时间戳 封装成类

C++学习之路: 时间戳 封装成类

 1 #ifndef TIMESTAMP_H 2 #define TIMESTAMP_H  3  4 #include <string> 5 #ifndef __STDC_FORMAT_MACROS 6 #define __STDC_FORMAT_MACROS 7 #endif /* __STDC_FORMAT_MACROS */ 8 #include <inttypes.h> 9 10 class Timestamp11 {12 public:13     Timestamp();14     Timestamp(int64_t value);15 16     bool isValid() const17     { return value_ > 0; }18 19     std::string toString() const;20     std::string toFormatString() const;  21 22     static Timestamp now();           //获取时间戳23 24 private:25     int64_t value_; //微秒级别的时间戳26 };27 28 29 #endif  /*TIMESTAMP_H*/

 

 

源文件

 

 1 #include "Timestamp.h" 2 #include <time.h> 3 #include <sys/time.h> 4 #include <stdio.h> 5 #include <string.h> 6 using namespace std; 7  8  9 Timestamp::Timestamp()10     :value_(0)11 {12 13 }14 15 Timestamp::Timestamp(int64_t value)16     :value_(value)17 {18 19 }20 21 string Timestamp::toString() const22 {23     //1411373695.48809624     int64_t sec = value_ / (1000 * 1000);25     int64_t usec = value_ % (1000 * 1000);26     // %06lld27     char text[32] = {0};28     snprintf(text, sizeof text, "%lld.%06lld", sec, usec);29 30     return string(text);31 }32 33 string Timestamp::toFormatString() const34 {35     //20140922 08:14:55.48809636     time_t sec = value_ / (1000 * 1000);37     int64_t usec = value_ % (1000 * 1000);38     struct tm st;39     //gmtime_r(&sec, &st);40     localtime_r(&sec, &st);         //localtime只是把时间戳转换为我们所熟知的 2014.7.40 xx:xx:xx 的格式 并不获取时间41 42     char text[100] = {0};43     snprintf(text, sizeof text, "%04d%02d%02d %02d:%02d:%02d.%06lld", st.tm_year + 1900, st.tm_mon + 1, st.tm_mday, st.tm_hour, st.tm_min44         , st.tm_sec, usec);45     return string(text);46 }47 48 Timestamp Timestamp::now()49 {50     struct timeval tv;51     memset(&tv, 0, sizeof tv);52     gettimeofday(&tv, NULL);           //获取时间戳偏移量53 54     int64_t val = 0;55     val += static_cast<int64_t>(tv.tv_sec) * 1000 * 1000;56     val += tv.tv_usec;57 58     return Timestamp(val);59 }

 

测试文件

 1 #include "Timestamp.h" 2 #include <iostream> 3 using namespace std; 4  5 int main(int argc, char const *argv[]) 6 { 7     Timestamp now = Timestamp::now(); 8  9     cout << now.toString() << endl;10     cout << now.toFormatString() << endl;11     return 0;12 }

 

C++学习之路: 时间戳 封装成类