calculate the days between two dates

前端 未结 2 1006
傲寒
傲寒 2021-01-29 13:18

I did a program that calculates the days different, between two dates, but I am not sure how can I add a statement that makes sure the program wont include the end date.

相关标签:
2条回答
  • 2021-01-29 13:43

    You can check if argv[7] is "include" using strcmp from <string.h>, and set a variable to ignore the end date if it's not

        /* Rest of the code above */
    
        if (mm2<mm1) {
            mm2 += 12;
            yyyy2 -= 1;
        }
    
        int include = 0;
        if (argc >= 8)
        {
            if (strcmp("include", argv[7]) == 0)
            {   
                include = 1;
            }
        }
    
        day_diff = dd2 - dd1;
        if (include == 0)
        {
            day_diff--;
        }
        printf("%d", day_diff);
    
        return 0;
    

    But i recommend you search about getopts, a flag seems more user friendly
    ./daysCalculatorA -i 19 2 2019 22 4 2019

    0 讨论(0)
  • 2021-01-29 14:00

    my code is calculating month and days but only printing days, its 86 days or 2 months and 25 days! how do i edit that so it shows 86?

    This is a typical case of "Don't (try to) reinvent the wheel." Use the Standard C mktime function to convert broken-down times into time values which can be subtracted from each other.

    #include <time.h>
    …
      time_t t1, t2;
      t1 = mktime(&(struct tm){ .tm_mday=dd1, .tm_mon=mm1-1, .tm_year=yyyy1-1900 });
      t2 = mktime(&(struct tm){ .tm_mday=dd2, .tm_mon=mm2-1, .tm_year=yyyy2-1900 });
      day_diff = (t2 - t1) / 24 / 60 / 60 + include;    // make days from seconds
    
    0 讨论(0)
提交回复
热议问题