C++中的日期运算

Date arithmetic in C++

本文关键字:运算 日期 C++      更新时间:2023-10-16

我一直在尝试编写一个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 );