我一直在尝试编写一个 C++ 程序,这需要我进行日期算术运算。 例如,今天的日期 (9-30-2014) 减去 4 天返回 9-26-2014,或者今天的日期加上 3 天返回 10-3-2014。 我原来的思路是用
时间
这将返回从 1970 年 1 月 1 日开始的以秒为单位的日期,然后我可以为天数加上或减去设定的秒数,并将结果传递给“put_time”的一部分
马尼普
开始我只是想让这个方法打印正确的日期,但我无法让编译器识别“put_time”
我使用的是eclipse版本(4.4.0) 使用“版本 4.1.11(2)-release (x86_64-unknown-cygwin)”作为编译器
根据研究,我发现“put_time”仅包含在某些版本的 c++ 中,我尝试运行此命令
`-std=c++0x`
但是我仍然收到相同的错误“'put_time' 未在此范围内声明”。
这是我目前运行的代码:
//============================================================================
// Name : Date.cpp
// Author : me
// Version :
// Copyright : Your copyright notice
// Description : date calculations
//============================================================================
#include <iostream>
#include <iomanip> // std::put_time
#include <ctime> // std::time_t, struct std::tm, std::localtime
#include <chrono> // std::chrono::system_clock
using namespace std;
int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
time_t timer;
time(&timer);
cout << timer;
struct tm * ptm = localtime(&timer);
cout << put_time(ptm,"%c");
return 0;
}
最佳答案
为什么不使用asctime
?它的原型(prototype)是 char* asctime (const struct tm * timeptr);
打印出 char* 应该没有任何问题。唯一的问题是输出格式固定为 Www Mmm dd hh:mm:ss yyyy
,其中 Www 表示星期几的三个字母缩写。
如果您希望输出字符串的格式更加灵活,您可以使用 strftime
来获得自定义格式。它的原型(prototype)是size_t strftime (char* ptr, size_t maxsize, const char* format,const struct tm* timeptr);
关于c++ - C++中的日期算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26129734/