您的位置:首页 > 运维架构 > Linux

Linux 下c++程序中打印系统当前时间

2017-04-03 11:58 399 查看
    //方案一,将当前时间折算为秒级,再通过相应的时间换算即可

    //此文件必须是c++文件

    /*

    #include<iostream>

    #include<ctime>

    using namespace std;

string now() {

 time_t t = time(0);

  char buffer[9] = {0};

   strftime(buffer, 9, "%H:%M:%S", localtime(&t));

    return string(buffer);

    }

    

    

    int main()

    {

    cout<<now()<<endl;

    return 0;

    }

*/

方法二:boost库中的:

#include <stdio.h>  // for sprintf()

#include <iostream>  // for console output

#include <string>  // for std::string

#include <boost/date_time/posix_time/posix_time.hpp>

//-----------------------------------------------------------------------------

// Format current time (calculated as an offset in current day) in this form:

//

//  "hh:mm:ss.SSS" (where "SSS" are milliseconds)

//-----------------------------------------------------------------------------

std::string now_str()

{

 // Get current time from the clock, using microseconds resolution

  const boost::posix_time::ptime now =

    boost::posix_time::microsec_clock::local_time();

     // Get the time offset in current day

      const boost::posix_time::time_duration td = now.time_of_day();

       //

        // Extract hours, minutes, seconds and milliseconds.

         //

          // Since there is no direct accessor ".milliseconds()",

           // milliseconds are computed _by difference_ between total milliseconds

            // (for which there is an accessor), and the hours/minutes/seconds

             // values previously fetched.
              //

   const long hours  = td.hours();

   const long minutes  = td.minutes();

    const long seconds  = td.seconds();

    const long milliseconds = td.total_milliseconds() -   ((hours * 3600 + minutes * 60 + seconds) * 1000);

                           //

                            // Format like this:

                             //

                              //  hh:mm:ss.SSS

                               //

                                // e.g. 02:15:40:321

                                 //

                                  //  ^   ^

                                   //  |   |

                                    //  123456789*12

                                     //  ---------10-  --> 12 chars + \0 --> 13 chars should suffice

                                      //

        char buf[40];

        sprintf(buf, "%02ld:%02ld:%02ld.%03ld",

         hours, minutes, seconds, milliseconds);

          return buf;
    }

测试:

   int main()

{

  std::cout << now_str() << '\n';

  }

                                             ///////////////////////////////////////////////////////////////////////////////
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: