利用C/C++ 标准库获取系统当前时间


  本文中结合C++11引入的日期时间处理库std::chrono和C语言的localtime()函数实现获取当前时间。 

  第一步,获取当前时间 

   system_clock::time_point now = std::chrono::system_clock::now();

  第二步,将当前时间转换为time_格式

  time_t tt = std::chrono::system_clock::to_time_t(now);

  第三步,将time_格式的时间转换为tm *格式   

  struct tm* tmNow = localtime(&tt);

  第四步,将tm*格式的时间转换为可读的时间  

  char date[20] = { 0 };
  sprintf(date, "%d-%02d-%02d %02d:%02d:%02d",(int)tmNow->tm_year + 1900, (int)tmNow->tm_mon + 1, (int)tmNow->tm_mday,  (int)tmNow->tm_hour, (int)tmNow->tm_min, (int)tmNow->tm_sec);

  最后,在C++中的话可以将char*字符串转换为std::string字符串来处理

  std::string timeNow(date);

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM