C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Structures in C

Compare two dates using structures

C Program: Compare two dates using structures

C

#include <stdio.h>

 

// Define structure for Date

struct Date {

    int day;

    int month;

    int year;

};

 

// Function declaration

int compareDates(struct Date d1, struct Date d2);

 

int main() {

    struct Date date1, date2;

    int result;

 

    // Input first date

    printf("Enter first date (DD MM YYYY): ");

    scanf("%d %d %d", &date1.day, &date1.month, &date1.year);

 

    // Input second date

    printf("Enter second date (DD MM YYYY): ");

    scanf("%d %d %d", &date2.day, &date2.month, &date2.year);

 

    // Compare the two dates

    result = compareDates(date1, date2);

 

    // Display result

    printf("\n--- Date Comparison Result ---\n");

    if (result == 0)

        printf("Both dates are equal.\n");

    else if (result == 1)

        printf("First date is later than the second date.\n");

    else

        printf("First date is earlier than the second date.\n");

 

    return 0;

}

 

// Function to compare two dates

int compareDates(struct Date d1, struct Date d2) {

    if (d1.year > d2.year)

        return 1;

    else if (d1.year < d2.year)

        return -1;

    else if (d1.month > d2.month)

        return 1;

    else if (d1.month < d2.month)

        return -1;

    else if (d1.day > d2.day)

        return 1;

    else if (d1.day < d2.day)

        return -1;

    else

        return 0;

}

Output

 
OUTPUT :
Enter first date (DD MM YYYY): 15 10 2025
Enter second date (DD MM YYYY): 20 09 2025

--- Date Comparison Result ---
First date is later than the second date.

Explanation

Concept

Description

struct Date

Holds day, month, and year as one logical unit.

compareDates()

Compares two Date structures and returns an integer: 1, -1, or 0.

Step-by-step comparison

Compares year → month → day in order of priority.

Return values

1 = first date later, -1 = first date earlier, 0 = equal.