1. 程式人生 > >Linux 下c++程式中列印系統當前時間

Linux 下c++程式中列印系統當前時間

    //方案一,將當前時間折算為秒級,再通過相應的時間換算即可
    //此檔案必須是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';

  }
                                             ///////////////////////////////////////////////////////////////////////////////