Created
January 16, 2025 19:37
-
-
Save leonid-ed/0673bd1f50a1789a469e9ebcfab3cea8 to your computer and use it in GitHub Desktop.
`datediff` is a simple C program that calculates the number of days between two dates provided in the format `YYYY-MM-DD`. It is a lightweight and efficient utility for quick date difference calculations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <time.h> | |
// Function to convert a date string to a struct tm | |
int parse_date(const char *date_str, struct tm *date) | |
{ | |
memset(date, 0, sizeof(struct tm)); | |
if (sscanf(date_str, "%4d-%2d-%2d", &date->tm_year, &date->tm_mon, | |
&date->tm_mday) != 3) { | |
return -1; // Error parsing date | |
} | |
date->tm_year -= 1900; // tm_year is years since 1900 | |
date->tm_mon -= 1; // tm_mon is zero-based | |
return 0; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
if (argc != 3) { | |
printf("Usage: %s <date1: YYYY-MM-DD> <date2: YYYY-MM-DD>\n", argv[0]); | |
return 1; | |
} | |
struct tm date1, date2; | |
time_t time1, time2; | |
// Parse the input dates | |
if (parse_date(argv[1], &date1) != 0 || parse_date(argv[2], &date2) != 0) { | |
printf("Invalid date format. Please use YYYY-MM-DD.\n"); | |
return 1; | |
} | |
// Convert struct tm to time_t | |
time1 = mktime(&date1); | |
time2 = mktime(&date2); | |
if (time1 == -1 || time2 == -1) { | |
printf("Error converting dates to time.\n"); | |
return 1; | |
} | |
// Calculate the difference in days | |
double day_gap = difftime(time2, time1) / (60 * 60 * 24); | |
printf("%.0f\n", day_gap); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment