一. 之前在Java中遇到了一些问题,就是Timestamp和字符串之间的互转(这里是用C++方法实现的,大家需要的话可以从我这边拿一份,有问题的话可以后台留言熬)
#include<iostream>
#include<sys/time.h>//这个头文件中是我们需要用到的一些时间函数
using namespace std;
class Timestamp{
private:
std::int64_t msec_;//当前时间戳的时间,精确到微秒
static const size_t BUFFLEN = 128;//最终格式化成字符串需要存储字符的数组
static const int KMSP = 1000*1000;//不同的情况我们返回不用的时间戳,如:一个需求是精确到毫秒,另外一个是精确到微秒
public:
Timestamp(std::int64_t m=0):msec_(m){
}//无参构造,初始化时间戳,给了一个默认的时间戳参数0
~Timestamp(){};//析构函数,因为我们没有涉及到空间的开辟或释放,所以此处只需要直接析构就可。大家可以给自己增加难度
Timestamp & now(){
*this = Timestamp::Now();//获取当前时间的话,我们可以自己封装一个函数
return *this;
}
void swap(Timestamp &other){//交换两个时间戳的函数,我们直接调用std中的swap函数
std::swap(this->msec_,other.msec_);
}
std::string toString() const{//转成字符串输出
char buff[BUFFLEN] = {0};//初始化我们格式化的数组
std::int64_t seconds = msec_ / KMSP;//这个是获取我们当前时间戳的秒数
std::int64_t microseconds = msec_ % KMSP;//这个是获取当前时间戳的毫秒数
snprintf(buff,BUFFLEN,"%lld.%06lld",seconds,microseconds);//sprintf函数可以将""引起来的东西格式化成字符串
return std::string (buff);//返回字符串
}
std::string toFormattedString(bool showms = true) const{//这个函数也是格式成年月日的格式
//默认需要输出当前时间戳的毫秒数
char buff[BUFFLEN] = {0};
std::int64_t seconds = msec_ / KMSP;//获取当前秒数
std::int64_t microseconds = msec_ % KMSP;//获取当前时间戳的毫秒数
struct tm tm_time{};
localtime_s(&tm_time,&seconds);
int pos = snprintf(buff,BUFFLEN,"%4d:%2d:%2d %2d-%2d-%2d",
1900+tm_time.tm_year,tm_time.tm_mon+1,tm_time.tm_mday,
tm_time.tm_hour,tm_time.tm_min,tm_time.tm_sec);//格式化,大家可以自己百度snprintf的用法
if(showms){
snprintf(buff+pos,BUFFLEN-pos,".%ldZ",microseconds);
}
return std::string(buff);
}
bool valid() const{
return msec_ > 0;
}//判断当前时间戳是否有效
std::int64_t ger_msec() const{
return msec_;
}//返回当前时间戳
time_t get_sec() const{
return static_cast<time_t>(msec_ / KMSP);
}//返回当前时间戳的秒数,此处用到了C++四种强制类型转换的一种,大家可以自己去百度
public:
bool operator<(const Timestamp &ts){
return this->msec_ < ts.msec_;
}//下面几个函数和这个差不读,都是判断两个时间戳的关系
bool operator==(const Timestamp &ts){
return this->msec_ == ts.msec_;
}
bool operator!=(const Timestamp &ts){
return !(*this == ts);
}
//s
std::int64_t operator-(const Timestamp &ts){
return static_cast<std::int64_t >((this->msec_ - ts.msec_)/KMSP);
}
std::int64_t diff_mesc(const Timestamp &ts){
return this->msec_ - ts.msec_;
}
Timestamp operator+(const std::int64_t seconds) const{
return Timestamp(this->msec_ + seconds*KMSP);
}
public:
static Timestamp Now(){
struct timeval tv = {};
gettimeofday(&tv, nullptr);
std::int64_t seconds = tv.tv_sec;
return Timestamp(seconds*KMSP + tv.tv_usec);
}
static Timestamp invalid(){
return Timestamp();
}
};
int main(){
Timestamp timestamp;
timestamp.now();
cout<<timestamp.toString()<<endl;
cout<<timestamp.toFormattedString()<<endl;
}