C++ 时间标记类

时间标记记录某一个瞬间时间

创建时间标记类:

    ——在事件发生时记录一个瞬间时间

    ——将时间标记作为整数打印

    ——将时间标记作为字符串打印

    ——将时间标记分解为年月日时分秒打印

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;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值