← back
Homeworks

Structs – Date

structs.c ✎ week 1

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

// the Date struct we made in class
struct Date {
    int day;
    int month;
    int year;
};


/*
 * function: is_valid_date
 * receives: a Date struct
 * does:     checks if the day and month are reasonable numbers
 * returns:  1 if valid, 0 if not
 */
int is_valid_date(struct Date d) {
    if (d.month < 1 || d.month > 12) {
        return 0;
    }
    if (d.day < 1 || d.day > 31) {
        return 0;
    }
    return 1;
}


/*
 * function: print_date
 * receives: a Date struct
 * does:     prints the date in DD/MM/YYYY format (from class)
 * returns:  nothing
 */
void print_date(struct Date d) {
    printf("%d/%d/%d\n", d.day, d.month, d.year);
}


/*
 * function: days_between
 * receives: two Date structs d1 and d2
 * does:     counts the days from d1 up to d2 one by one
 * returns:  the number of days between them
 */
int days_between(struct Date d1, struct Date d2) {
    // days each month has
    int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    int count = 0;
    struct Date current = d1;

    // we assume d1 is before d2
    // keep adding one day until we reach d2
    while (current.year != d2.year || current.month != d2.month || current.day != d2.day) {
        current.day++;
        if (current.day > month_days[current.month - 1]) {
            current.day = 1;
            current.month++;
        }
        if (current.month > 12) {
            current.month = 1;
            current.year++;
        }
        count++;
    }

    return count;
}


/*
 * function: days_until
 * receives: a Date struct (a future date)
 * does:     gets todays date from the computer, then uses days_between to
 *           find how many days are left until the given date
 * returns:  number of days remaining
 */
int days_until(struct Date target) {
    // get todays date (copied from stack overflow)
    time_t t = time(NULL);
    struct tm *today_tm = localtime(&t);

    struct Date today;
    today.day   = today_tm->tm_mday;
    today.month = today_tm->tm_mon + 1;
    today.year  = today_tm->tm_year + 1900;

    return days_between(today, target);
}


int main() {
    struct Date d1 = {1, 1, 2025};
    struct Date d2 = {1, 3, 2025};

    printf("date 1: ");
    print_date(d1);
    printf("date 2: ");
    print_date(d2);

    printf("is d1 valid: %d\n", is_valid_date(d1));

    printf("days between d1 and d2: %d\n", days_between(d1, d2));

    struct Date future = {31, 12, 2025};
    printf("days until 31/12/2025: %d\n", days_until(future));

    return 0;
}