This repository has been archived on 2026-07-19. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
acquire-core-migration/legacy/app/common/util_date.c

52 lines
1.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define DATE_BUF_SIZE 32
typedef struct {
int year;
int month;
int day;
} date_t;
int date_parse(const char* str, date_t* out) {
if (!str || !out) return -1;
return sscanf(str, "%4d-%2d-%2d", &out->year, &out->month, &out->day);
}
int date_format(const date_t* d, char* buf, size_t len) {
if (!d || !buf) return -1;
return snprintf(buf, len, "%04d-%02d-%02d", d->year, d->month, d->day);
}
int date_diff_days(const date_t* from, const date_t* to) {
if (!from || !to) return 0;
struct tm a = {0}, b = {0};
a.tm_year = from->year - 1900; a.tm_mon = from->month - 1; a.tm_mday = from->day;
b.tm_year = to->year - 1900; b.tm_mon = to->month - 1; b.tm_mday = to->day;
return (int)(difftime(mktime(&b), mktime(&a)) / 86400);
}
int date_add_days(const date_t* d, int days, date_t* out) {
if (!d || !out) return -1;
struct tm base = {0};
base.tm_year = d->year - 1900; base.tm_mon = d->month - 1; base.tm_mday = d->day;
base.tm_mday += days;
mktime(&base);
out->year = base.tm_year + 1900;
out->month = base.tm_mon + 1;
out->day = base.tm_mday;
return 0;
}
int date_today(date_t* out) {
if (!out) return -1;
time_t now = time(NULL);
struct tm* t = localtime(&now);
out->year = t->tm_year + 1900;
out->month = t->tm_mon + 1;
out->day = t->tm_mday;
return 0;
}