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 Timestamp 11 { 12 public: 13 Timestamp(); 14 Timestamp(int64_t value); 15 16 bool isValid() const 17 { 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() const 22 { 23 //1411373695.488096 24 int64_t sec = value_ / (1000 * 1000); 25 int64_t usec = value_ % (1000 * 1000); 26 // %06lld 27 char text[32] = {0}; 28 snprintf(text, sizeof text, "%lld.%06lld", sec, usec); 29 30 return string(text); 31 } 32 33 string Timestamp::toFormatString() const 34 { 35 //20140922 08:14:55.488096 36 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_min 44 , 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 }
时间: 2024-10-20 14:46:55