IZP/Cviko5_1/main.c
2024-11-21 17:14:54 +01:00

86 lines
2.5 KiB
C

#include "types.h"
#include <stdio.h>
bool is_leap_year(int year) {
return (year % 4 == 0 && year % 100 != 0) ||
(year % 4 == 0 && year % 400 == 0);
}
/**
* Determine whether the provided date is valid.
*
* @param date Datová struktura reprezentující datum
*
* @return `true` v případě validního data, `false` jinak
*/
bool is_valid_date(struct date_t date) {
return !(date.day > 31 || date.day < 1 || date.month > 12 || date.month < 1 ||
(date.month == 2 && date.day > 29 && is_leap_year(date.year)) ||
(date.month == 2 && date.day > 28 && !is_leap_year(date.year)) ||
date.year < 1582 || date.year > 2024 ||
((date.month == 4 || date.month == 6 || date.month == 9 ||
date.month == 11) &&
date.day > 30));
}
/**
* Find the earlier date by comparing years, months and days.
*
* @param date1 Datová struktura reprezentující první datum
* @param date2 Datová struktura reprezentující druhé datum
*
* @return `DATE1_IS_EARLIER` v případě date1 je dřívější,
* `DATE1_IS_LATER` když date2 je dřívější,
* `DATES_ARE_EQUAL` jinak (data jsou stejná)
*/
int earlier_date(struct date_t date1, struct date_t date2) {
// TODO: implementujte funkci dle zadání
if (date1.year == date2.year && date1.month == date2.month &&
date1.day == date2.day) {
return DATES_ARE_EQUAL;
}
if (date1.year < date2.year ||
(date1.year == date2.year && date1.month < date2.month) ||
(date1.year == date2.year && date1.month == date2.month &&
date1.day < date2.day)) {
return DATE1_IS_EARLIER;
}
return DATE1_IS_LATER;
}
#ifndef TEST_BUILD
int main(void) {
struct date_t date1, date2;
// Load two dates from the user
printf("Provide the first date (format yyyy-mm-dd): ");
scanf("%d-%d-%d", &date1.year, &date1.month, &date1.day);
printf("Provide the second date (format yyyy-mm-dd): ");
scanf("%d-%d-%d", &date2.year, &date2.month, &date2.day);
// Check that the dates are valid
if (!is_valid_date(date1) || !is_valid_date(date2)) {
printf("Invalid date!\n");
return 1;
}
// Compare the dates and find the earlier one
int earlier = earlier_date(date1, date2);
if (earlier == DATE1_IS_EARLIER) {
printf("The date %d-%d-%d is earlier.\n", date1.year, date1.month,
date1.day);
} else if (earlier == DATE1_IS_LATER) {
printf("The date %d-%d-%d is earlier.\n", date2.year, date2.month,
date2.day);
} else {
printf("The dates are the same.\n");
}
return 0;
}
#endif