Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

Calculate the end date from start date and number of days in C

for the past few hours I've been trying to figure out how to write a programme in C to calculate the end date based on the start date and number of days. (I haven't found the forum for this exact problem, yet). So let's say you input 27/1/2021 as the starting date and then 380 days. The programme should now calculate and show you the end date 11/2/2022. I don't know how to move forward, the help would be appreciated.

#include <stdio.h>
#include <stdlib.h>

int day, month, year, numberDays;

int leapYear(int year) {
    return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}

int monthYear[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

int main(void) {

    printf("Enter starting date: ");
    scanf("%d %d %d", &day, &month, &year);

    printf("Enter number of days: ");
    scanf("%d", &numberDays);

    leapYear(year);

    int wholeYears, rest;
    if (leapYear(year)) {
        wholeYears = numberDays / 366;
        rest = numberDays % 366;
    }
    else {
        wholeYears = numberDays / 365;
        rest = numberDays % 365;
    }
    int resultYears = year + wholeYears;
    int midDays = day + rest;
    int resultMonths;

    return 0;
}

I can't move any further. I'd need help.

question from:https://stackoverflow.com/questions/65927901/calculate-the-end-date-from-start-date-and-number-of-days-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So let's say you input 27/1/2021 as the starting date and then 380 days. The programme should now calculate and show you the end date 11/2/2022.

An easy approach is to use mktime() to bring a date into its standard range.

#include <stdio.h>
#include <time.h>

int main(void) {
  struct tm start = {.tm_year = 2021 - 1900, .tm_mon = 1 - 1, .tm_mday = 27,
      .tm_hour = 12};  // Midday to avoid DST issues.
  start.tm_mday += 380;
  printf("%d/%d/%d
", start.tm_mday, start.tm_mon + 1, start.tm_year + 1900);
  time_t t = mktime(&start);
  printf("%d/%d/%d %s
", start.tm_mday, start.tm_mon + 1, start.tm_year + 1900, 
      t == -1 ? "failed" : "OK");
}

Output

407/1/2021
11/2/2022 OK

Otherwise with discrete code, one is effectively re-writing the year/month/day portion of mktime().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...