时间标记记录某一个瞬间时间
创建时间标记类:
——在事件发生时记录一个瞬间时间
——将时间标记作为整数打印
——将时间标记作为字符串打印
——将时间标记分解为年月日时分秒打印
TimeStamp.h
#include<iostream>
#include<ctime>
#include<string>
using namespace std;
class TimeStamp{
public:
void set(long s = 0){
if(s <= 0)
stamp = time(0);
else
stamp = s;
}
time_t get() const { return stamp; }
string getAsString() const {return extract(0, 24);}
string getYear() const {return extract(20, 4);}
string getMonth() const {return extract(4, 3);}
string getDay() const {return extract(0, 3);}
string getHour() const {return extract(11, 2);}
string getMinute() const {return extract(14, 2);}
string getSecond() const {return extract(17, 2);}
private:
string extract(int offset, int count) const{
string timeString = ctime(&stamp);
return timeString.substr(offset, count);
}
time_t stamp;
};
test.cpp
#include "TimeStamp.h"
void dumpTs(const TimeStamp&);
int main()
{
TimeStamp ts;
time_t now=time(0);
ts.set();
dumpTs(ts);
ts.set(now+200000);
dumpTs(ts);
ts.set(now-300000);
dumpTs(ts);
ts.set(-999);
dumpTs(ts);
return 0;
}
void dumpTs(const TimeStamp& ts){
cout<<endl<<"Testing method:"<<endl;
cout<<"\t"<<ts.get()<<endl;
cout<<"\t"<<ts.getAsString()<<endl;
cout<<"\t"<<ts.getYear()<<endl;
cout<<"\t"<<ts.getMonth()<<endl;
cout<<"\t"<<ts.getDay()<<endl;
cout<<"\t"<<ts.getHour()<<endl;
cout<<"\t"<<ts.getMinute()<<endl;
cout<<"\t"<<ts.getSecond()<<endl;
}