简单C++ 时间戳类

简单C++ 时间戳类,第1张

简单C++ 时间戳类 C++时间函数
#include 
#include 
#include 
#include 
using namespace std;


class HistoryCache
{
public:
   static std::string getTimeStamp(time_t epochTime, const char* format = "%Y-%m-%d %H:%M:%S")
   {
      char timestamp[64] = {0};
      strftime(timestamp, sizeof(timestamp), format, localtime(&epochTime));
      return timestamp;
   }

   static time_t convertTimeToEpoch(const char* theTime, const char* format = "%Y-%m-%d %H:%M:%S")
   {
      std::tm tmTime;
      memset(&tmTime, 0, sizeof(tmTime));
      strptime(theTime, format, &tmTime);
      return mktime(&tmTime);
   }
};

int main()
{
    // get current epoch time
    const time_t curTime = time(0);

   // convert current time to a string
   std::string curTimeStr = HistoryCache::getTimeStamp(curTime);

   // convert string time to an epoch time
    const time_t curTime2 = HistoryCache::convertTimeToEpoch(curTimeStr.c_str());
   // display results
   std::cout << "Epoch Time: " << curTime    << "n" << "As string : " << curTimeStr << "n"  << "Epoch Time: " << curTime2  << std::endl;
}

结果:

[root@jn cpp]# g++ time.cpp 
[root@jn cpp]# ./a.out 
Epoch Time: 1619351221
As string : 2021-04-25 19:47:01
Epoch Time: 1619351221
[root@jn cpp]# 
C++时间函数

m_time.cpp:

#include 
#include 
#include 

extern"C"
{
#include 
}

class timeKit
{
public:
        timeKit(){
                buffer = new char[20];
                //TM = new struct tm;
        }

        ~timeKit(){
                if (buffer) {
                        delete[] buffer;
                }

                if (TM) {
                        //delete TM;
                }
        }

        inline std::string TimeStr() {
                Epoch();
                TM = localtime(&m_Time);
                strftime(buffer, 20, "%Y-%m-%d %H:%M:%S", TM);
                return m_TimeStr = std::string(buffer) + " ";
        }

        inline time_t Epoch(){ time(&m_Time); return m_Time;}
private:
        //std::atomic m_lock;
        char*  buffer;
        struct tm *TM;
        time_t m_Time;
        std::string m_TimeStr;
};


#ifdef dujn_debug
using namespace std;


int main(){
    timeKit mt;
    //cout << mt.getEpoch() << " : start" << endl;
    cout << mt.TimeStr() << " : 万丈高楼平地起"<< endl;
}
#endif

结果:

[root@jn cpp]# g++ m_time.cpp -Ddujn_debug -std=c++11
[root@jn cpp]# ./a.out
2021-11-03 11:01:16 : 万丈高楼平地起
[root@jn cpp]#

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5099859.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存