C++中的日期运算
Date arithmetic in C++
我一直在尝试编写一个C++程序,这需要我进行日期运算。例如,今天的日期(9-30-2014)减去4天并返回9-26-2014,或者今天的日期加3天返回10-3-2014。我最初的想法是使用
ctime
它将以秒为单位返回1970年1月1日的日期,然后我可以添加或减去一组秒数作为天数,并将结果传递到的一部分"put_time"中
iomanip
首先,我只是想让这个方法打印正确的日期,但我无法让编译器识别"put_time"
我使用的是eclipse版本(4.4.0)使用"版本4.1.11(2)-发行版(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
?它的原型是char* asctime (const struct tm * timeptr);
,打印出字符应该不会有任何问题。唯一的问题是输出格式固定为Www Mmm dd hh:mm:ss yyyy
,其中Www表示一周中某一天的三个字母缩写。
如果您希望在输出字符串的格式上有更大的灵活性,可以使用strftime
来获得自定义格式。它的原型是size_t strftime (char* ptr, size_t maxsize, const char* format,const struct tm* timeptr );
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 查询SQLite数据库中的日期
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- GCC本机矩阵运算库
- Log4cpp:以UTC/GMT时区打印日期
- 位阵列上的快速AND运算
- 字符串中int的加法运算
- 使用C++的日期库读取时间
- 算术运算的结果类似于:C浮点变量中的1/3
- 如何使用OpenMP并行化此矩阵时间矢量运算
- 日期格式为C++
- 如何在两个 boost::multi_arrays (C++) 之间执行数学运算?
- 如何在 C++20 计时中为日期添加天数?
- 如何在QTableView中排序和更改日期格式
- 如何在cpp中使用地图显示给定日期范围内(在下面的问题中)的费率?
- Gtkmm 会不断检查 Gtk::日历上的所选日期是否发生变化
- 如何在 vtk Poly 数据上进行布尔运算?
- fmt 与 Howard Hinnant 的日期:为什么从 fmt::to_string "{}"?FMT 和日期的最佳实践?
- 使用按位运算从整数日期 (yyyyMMdd) 中提取月份
- C++中的日期运算