在c++中是否有跨平台的方法来获取当前的日期和时间?
当前回答
总有__TIMESTAMP__预处理器宏。
#include <iostream>
using namespace std
void printBuildDateTime () {
cout << __TIMESTAMP__ << endl;
}
int main() {
printBuildDateTime();
}
例:2014年4月13日太阳11:28:08
其他回答
std C库提供time()。 这是从纪元开始的秒数,可以使用标准C函数转换为日期和H:M:S。Boost还有一个时间/日期库供您检查。
time_t timev;
time(&timev);
(给谷歌人)
还有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 <iostream>
#include <string>
#include <stdio.h>
#include <time.h>
// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
return buf;
}
int main() {
std::cout << "currentDateTime()=" << currentDateTime() << std::endl;
getchar(); // wait for keyboard input
}
输出:
currentDateTime()=2012-05-06.21:47:59
有关日期/时间格式的更多信息,请访问这里
http://www.cplusplus.com/reference/ctime/strftime/
这个内置功能似乎提供了一组合理的选项。
总有__TIMESTAMP__预处理器宏。
#include <iostream>
using namespace std
void printBuildDateTime () {
cout << __TIMESTAMP__ << endl;
}
int main() {
printBuildDateTime();
}
例:2014年4月13日太阳11:28:08
推荐文章
- 为什么这个结合赋值和相等检查的if语句返回true?
- cplusplus.com给出的错误、误解或坏建议是什么?
- 找出质数最快的算法是什么?
- 如何减去日期/时间在JavaScript?
- c++枚举类可以有方法吗?
- 将Date对象转换为日历对象
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- 将缺失的日期添加到熊猫数据框架中
- 如何防止ifelse()从日期对象转化为数字对象
- 在函数的签名中添加关键字
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- 为什么在标准容器中使用std::auto_ptr<>是错误的?