1 #ifndef Timestamp_h2 #defineTimestamp_h3 4#include <string>5 #ifndef __stdc_format_macros6 #define__stdc_format_macros7 #endif/* __stdc_format_macros */8#include <inttypes.h>9 Ten classTimestamp One { A Public: - Timestamp (); - Timestamp (int64_t value); the - BOOLIsValid ()Const -{returnValue_ >0; } - +STD::stringToString ()Const; -STD::stringToformatstring ()Const; + A StaticTimestamp now ();//Get time stamp at - Private: -int64_t Value_;//time stamp at microsecond level - }; - - in #endif/*timestamp_h*/
source file
1#include"Timestamp.h"2#include <time.h>3#include <sys/time.h>4#include <stdio.h>5#include <string.h>6 using namespacestd;7 8 9 Timestamp::timestamp ()Ten: Value_ (0) One { A - } - the Timestamp::timestamp (int64_t value) - : Value_ (value) - { - + } - + stringTimestamp::tostring ()Const A { at //1411373695.488096 -int64_t sec = value_/( +* +); -int64_t usec = value_% ( +* +); - //%06lld - Chartext[ +] = {0}; -snprintf (Text,sizeofText"%lld.%0 6lld", sec, usec); in - return string(text); to } + - stringTimestamp::toformatstring ()Const the { * //20140922 08:14:55.488096 $time_t sec = value_/( +* +);Panax Notoginsengint64_t usec = value_% ( +* +); - structTM St; the //Gmtime_r (&sec, &st); +Localtime_r (&sec, &st);//LocalTime just converts the timestamp to the format we know 2014.7.40 xx:xx:xx and does not get the time A the Chartext[ -] = {0}; +snprintf (Text,sizeofText"%04d%02d%02d%02d:%02d:%02d.%0 6lld", St.tm_year +1900, St.tm_mon +1, St.tm_mday, St.tm_hour, St.tm_min - , St.tm_sec, usec); $ return string(text); $ } - - Timestamp Timestamp::now () the { - structTimeval TV;Wuyimemset (&TV,0,sizeofTV); theGettimeofday (&TV, NULL);//get timestamp offset - Wuint64_t val =0; -Val + = static_cast<int64_t> (tv.tv_sec) * +* +; AboutVal + =tv.tv_usec; $ - returnTimestamp (val); -}
Test file
1#include"Timestamp.h"2#include <iostream>3 using namespacestd;4 5 intMainintargcChar Const*argv[])6 {7Timestamp now =Timestamp::now ();8 9cout << now.tostring () <<Endl;Tencout << now.toformatstring () <<Endl; One return 0; A}
C + + Learning path: Timestamp encapsulation into class