栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

简单C++ 时间戳类

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

简单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]#
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/429992.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号