在c++中是否有跨平台的方法来获取当前的日期和时间?
当前回答
(给谷歌人)
还有Boost::date_time:
#include <boost/date_time/posix_time/posix_time.hpp>
boost::posix_time::ptime date_time = boost::posix_time::microsec_clock::universal_time();
其他回答
(给谷歌人)
还有Boost::date_time:
#include <boost/date_time/posix_time/posix_time.hpp>
boost::posix_time::ptime date_time = boost::posix_time::microsec_clock::universal_time();
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
下面是不弃用的现代c++解决方案,用于将时间戳作为std::string用于例如文件名:
std::string get_file_timestamp()
{
const auto now = std::chrono::system_clock::now();
const auto in_time_t = std::chrono::system_clock::to_time_t(now);
std::stringstream output_stream;
struct tm time_info;
const auto errno_value = localtime_s(&time_info, &in_time_t);
if(errno_value != 0)
{
throw std::runtime_error("localtime_s() failed: " + std::to_string(errno_value));
}
output_stream << std::put_time(&time_info, "%Y-%m-%d.%H_%M_%S");
return output_stream.str();
}
std C库提供time()。 这是从纪元开始的秒数,可以使用标准C函数转换为日期和H:M:S。Boost还有一个时间/日期库供您检查。
time_t timev;
time(&timev);
从c++ 11开始,你可以使用std::chrono::system_clock::now()
示例(复制自en.cppreference.com):
#include <iostream>
#include <chrono>
#include <ctime>
int main()
{
auto start = std::chrono::system_clock::now();
// Some computation here
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished computation at " << std::ctime(&end_time)
<< "elapsed time: " << elapsed_seconds.count() << "s"
<< std::endl;
}
这应该打印如下内容:
finished computation at Mon Oct 2 00:59:08 2017
elapsed time: 1.88232s