c++日期差异

C++ date difference-

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

我有字符串格式的日期-例如-

string date1= "06/12/2014"
string date2= "06/12/2015"

现在我的要求是找出这两个日期之间的差天数(date2-date1) -

必须在c++代码中使用-

任何快速的帮助将是感激的-谢谢

标准库做得很好

阅读手册

#include <iostream>
#include <ctime>
#include <string>
#include <sstream>
#include <memory>
using namespace std;
void toTM(string date, struct tm *t) {
    stringstream ss(date);
    string month, day, year;
    getline(ss, month, '/');
    getline(ss, day, '/');
    getline(ss, year, '/');
    memset(t, 0, sizeof(struct tm));
    t->tm_mday = stoi(day);
    t->tm_mon = stoi(month) - 1;
    t->tm_year = stoi(year) - 1900;
}

int main(int argc, char** argv) {
    string date1 = "06/12/2014";
    string date2 = "06/12/2015";
    struct tm time1, time2;
    toTM(date1, &time1);
    toTM(date2, &time2);
    int diff = difftime(mktime(&time2), mktime(&time1));
    cout << diff / 60 / 60 / 24 << " days" << endl;
    return EXIT_SUCCESS;
}