muduo 11 Timestamp时间管理

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

目录

成员变量:

构造函数:

Timestamp::now()显示当前时间

Timestamp::toString()格式转换

Timestamp::toFormattedString(bool showMicroseconds)

Timestamp.h

Timestamp.cc

时间戳比较运算符重载

测试:


      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(&microSecondsSinceRpoch_);
    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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值