目录
Timestamp::toFormattedString(bool showMicroseconds)
Timestamp类,在这个类中我们主要要完成两个内容,返回当前时间的时间戳time_t类型,并将其转化成字符串类型。
成员变量:
![]()
底层成员变量是一个int64_t位的记录事件的整数microSecondsSinceRpoch_。
构造函数:

实现了两个构造函数,一个默认构造函数,一个传入参数的构造函数。
Timestamp::now()显示当前时间

定义一个整数类型time_t由time(NULL)返回当前时间,以秒为单位。同时返回Timestamp对象。
time函数 :返回自 Epoch(1970年1月1日 00:00:00 UTC)以来经过的秒数
Timestamp::toString()格式转换

该函数用于将时间戳转换成本地时间类型:
struct tm* localtime(const time_t* timer);
Timestamp::toFormattedString(bool showMicroseconds)
showMicroseconds决定是否在返回的格式化字符串中显示微秒部分。

Timestamp.h
#pragma once
#include <iostream>
#include <string>
class Timestamp
{
public:
// 默认构造函数
Timestamp();
// 带参数的构造函数
explicit Timestamp(int64_t microSecondsSinceRpoch_);
//显示当前时间戳 并返回一个Timestamp对象
static Timestamp now();
//格式转化方法 将字符串转化成时间字符串
std::string toString() const;
private:
int64_t microSecondsSinceRpoch_;
};
Timestamp.cc
#include "Timestamp.h"
#include <time.h>
Timestamp::Timestamp()
:microSecondsSinceRpoch_(0)
{}
// 带参数的构造函数
Timestamp::Timestamp(int64_t microSecondsSinceRpoch)
: microSecondsSinceRpoch_(microSecondsSinceRpoch)
{}
//显示当前时间
Timestamp Timestamp::now()
{
time_t timenow = time(NULL);
return Timestamp(timenow);
}
//格式转化方法 将字符串转化成时间字符串
std::string Timestamp::toString() const
{
char buf[128] = {0};
tm * tm_time = localtime(µSecondsSinceRpoch_);
snprintf(buf,128,"%4d/%02d/%02d %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;
}
时间戳比较运算符重载
测试:
使用的时候我在日志系统中调用:
Timestamp::now().toString()
#include <iostream>
int main()
{
std::cout<<Timestamp::now().toString()<<std::endl;
return 0;
}

本文介绍了Timestamp类的设计,包括成员变量microSecondsSinceRpoch_存储微秒数,构造函数,now()方法获取当前时间,toString()和toFormattedString()用于时间戳到字符串的转换。文章还提及了时间戳的比较运算符重载,并展示了在日志系统中的应用示例。

1176

被折叠的 条评论
为什么被折叠?



