头文件
#ifndef _TIMESTAMP_H_
#define _TIMESTAMP_H_
#include <iostream>
#include <string>
class Timestamp {
public:
Timestamp(); // 默认构造
explicit Timestamp(int64_t microSecondsSinceEpoch_); // 有参构造
static Timestamp now(); // 获取当前时间
std::string toString() const; // toString方法
private:
int64_t microSecondsSinceEpoch_; // 数据
};
#endif
源文件
#include "Timestamp.h"
#include <time.h>
// 默认构造
Timestamp::Timestamp():microSecondsSinceEpoch_(0){}
// 有参构造
Timestamp::Timestamp(int64_t microSecondsSinceEpoch_):microSecondsSinceEpoch_(microSecondsSinceEpoch_){}
// 获取当前时间
Timestamp Timestamp::now()
{
return Timestamp(time(NULL)); // 获取当前时间
}
// toString方法
std::string Timestamp::toString() const
{
char buf[128] = {0};
tm* tm_time = localtime(µSecondsSinceEpoch_); // 获取当前时间
// 拼接年/月/日 时:分:秒
snprintf(buf, 128, "%4d/%02d/%2d %02d:%02d:%02d",
tm_time->tm_year + 1900,
tm_time->tm_mon + 1,
tm_time->tm_mday,
tm_time->tm_hour,
tm_time->tm_min,
tm_time->tm_sec);
return buf;
}
测试
// 测试一下
#include <iostream>
#include "Time.h"
int main(int argc, char** argv) {
std::cout << Timestamp::now().toString() << std::endl;
return 0;
}
?这里用到了tm这个类,查看源码
#ifndef __struct_tm_defined
#define __struct_tm_defined 1
#include <bits/types.h>
/* ISO C `broken-down time' structure. */
struct tm
{
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/
# ifdef __USE_MISC
long int tm_gmtoff; /* Seconds east of UTC. */
const char *tm_zone; /* Timezone abbreviation. */
# else
long int __tm_gmtoff; /* Seconds east of UTC. */
const char *__tm_zone; /* Timezone abbreviation. */
# endif
};
#endif
|