时间&日期
##MyTime.hpp
#pragma once
#include <iostream>
#include <ctime>
#include <string>using namespace std;class MyTime
{
public:MyTime() {};~MyTime() {};time_t timeSec(void);uint64_t timeMs(void);string timeDate(void);
};
##MyTime.cpp
#include "MyTime.hpp"
#include <sys/timeb.h>time_t MyTime::timeSec(void)
{return time(NULL);
}uint64_t MyTime::timeMs(void)
{timeb now;ftime(&now);return (now.time * 1000 + now.millitm);
}
//# 注:Linux下使用gettimeofday()函数获取后计算实现
/*
#include<sys/time.h>struct timeval tv;
gettimeofday(&tv,NULL);tv.tv_sec*1000 + tv.tv_usec/1000;
*/string MyTime::timeDate(void)
{time_t now = time(NULL);struct tm ltm;localtime_s(<m, &now);int year = 1900 + ltm.tm_year;int mon = 1 + ltm.tm_mon;int mday = ltm.tm_mday;int hour = ltm.tm_hour;int min = ltm.tm_min;int sec = ltm.tm_sec;string timeDate = to_string(year) + "-" + to_string(mon) + "-" + to_string(mday) + " " +to_string(hour) + ":" + to_string(min) + ":" + to_string(sec);return timeDate;
}
##测试函数
void test_time(void)
{MyTime myTime;cout << myTime.timeSec() << endl;cout << myTime.timeMs() << endl;cout << myTime.timeDate() << endl;
}
##测试结果截图