2

How to count days between two dates. Dates ar hold in integer variables (array). If there is some function would be great. If no, I have trying something with for loops, but didn't found right algorithm.

#include <iostream>

int stoi(std::string s);
int main(){
    /* 5th november of 2013 */
    int days1[0] = 05;
    int days1[1] = 11;
    int days1[2] = 2013;
    /* 7th october of 2016 */
    int days2[0] = 07;
    int days2[1] = 10;
    int days2[2] = 2016;
    int days = date(days1,days2);
    std::cout << days << std::endl;
    return 0;
}
int date(int dates1[], int date2[]){
    int days = 0;
    /* Task: how much days is past */
    /* Days in each month must be real (31 or 30 or 29/28) */
    /* there can't be constant as 31 days on each month or 365 days in year */
    return days;
}

2 Answers2

0

You may find this epoch calculator code of interest. Written in C, but easily converted to C++.

Community
  • 1
  • 1
gOnZo
  • 489
  • 4
  • 15
0
#include <iostream>
#include <ctime>
#include <cmath>


auto date(int date1[], int date2[]){
    std::tm dur[2] {{0,0,0,date1[0],date1[1]-1,date1[2]-1900},{0,0,0,date2[0],date2[1]-1,date2[2]-1900}};
    std::time_t t1 {std::mktime(dur)}, t2 {std::mktime(dur+1)};
    if ( t1 != (std::time_t)(-1) && t2 != (std::time_t)(-1) ){
        return std::difftime(t2, t1) / (60 * 60 * 24);
    }else{
        return (double)INFINITY;
    //alternative: throw exception
    }
}
int main(){
    /* 5th november of 2013 */
    int days1[] = {5,11,2013};
    /* 7th october of 2016 */
    int days2[] = {7,10,2016};
    auto days = date(days1,days2);
    if(std::isinf(days)){
        std::cout << "cannot convert to time_t" << std::endl;
    }else{
        std::cout << days << std::endl;
    }
    return 0;
}

This should print 1067.

cshu
  • 5,654
  • 28
  • 44