66 lines
1.6 KiB
C
66 lines
1.6 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <time.h>
|
|
|
|
typedef struct {
|
|
int year;
|
|
int month;
|
|
int day;
|
|
} Date;
|
|
|
|
Date* date_create(int year, int month, int day) {
|
|
Date* d = (Date*)malloc(sizeof(Date));
|
|
d->year = year;
|
|
d->month = month;
|
|
d->day = day;
|
|
return d;
|
|
}
|
|
|
|
void date_free(Date* d) {
|
|
free(d);
|
|
}
|
|
|
|
char* date_to_string(Date* d) {
|
|
char* buf = (char*)malloc(11);
|
|
sprintf(buf, "%04d-%02d-%02d", d->year, d->month, d->day);
|
|
return buf;
|
|
}
|
|
|
|
Date* date_from_string(const char* str) {
|
|
Date* d = (Date*)malloc(sizeof(Date));
|
|
sscanf(str, "%d-%d-%d", &d->year, &d->month, &d->day);
|
|
return d;
|
|
}
|
|
|
|
int date_diff_days(Date* a, Date* b) {
|
|
struct tm ta = {0}, tb = {0};
|
|
ta.tm_year = a->year - 1900; ta.tm_mon = a->month - 1; ta.tm_mday = a->day;
|
|
tb.tm_year = b->year - 1900; tb.tm_mon = b->month - 1; tb.tm_mday = b->day;
|
|
time_t tta = mktime(&ta);
|
|
time_t ttb = mktime(&tb);
|
|
return (int)((tta - ttb) / 86400);
|
|
}
|
|
|
|
int date_compare(Date* a, Date* b) {
|
|
if (a->year != b->year) return a->year - b->year;
|
|
if (a->month != b->month) return a->month - b->month;
|
|
return a->day - b->day;
|
|
}
|
|
|
|
Date* date_add_days(Date* d, int days) {
|
|
struct tm tm = {0};
|
|
tm.tm_year = d->year - 1900;
|
|
tm.tm_mon = d->month - 1;
|
|
tm.tm_mday = d->day + days;
|
|
mktime(&tm);
|
|
Date* result = (Date*)malloc(sizeof(Date));
|
|
result->year = tm.tm_year + 1900;
|
|
result->month = tm.tm_mon + 1;
|
|
result->day = tm.tm_mday;
|
|
return result;
|
|
}
|
|
|
|
int date_get_year(Date* d) { return d->year; }
|
|
int date_get_month(Date* d) { return d->month; }
|
|
int date_get_day(Date* d) { return d->day; }
|