libepoch/datetime.c
2024-02-05 19:12:51 -05:00

46 lines
1.3 KiB
C

#include "epoch.h"
#include <stdint.h>
#include <time.h>
int32_t dateTimeGetYear(DateTime *self) {
return self->year.year;
}
int64_t dateTimeGetTimestampNaive(DateTime *self) {
int64_t seconds = 0;
Year year = (Year){ .tag = normalYear, .year = 1970 };
Month month = January;
int32_t oldyear = yearGetInner(&self->year);
if (oldyear < 1970) {
while (yearGetInner(&year) > oldyear) {
yearDecrement(&year);
seconds -= yearGetSeconds(&year);
}
} else if (oldyear > 1970) {
while (yearGetInner(&year) < oldyear) {
seconds += yearGetSeconds(&year);
yearIncrement(&year);
}
}
while (month < self->month) {
seconds += monthGetSeconds(month, &self->year);
monthIncrement(&month);
}
seconds += ((int64_t)self->day - 1) * SECONDS_PER_DAY;
seconds += (int64_t)self->hour * SECONDS_PER_HOUR;
seconds += (int64_t)self->minute * 60;
seconds += (int64_t)self->second;
return seconds;
}
int64_t dateTimeGetTimestamp(DateTime *self) {
int64_t seconds = dateTimeGetTimestampNaive(self);
seconds += timezoneAsSeconds(&self->zone);
return seconds;
}
void dateTimeGetTimeval(DateTime *self, struct timespec * ts) {
ts->tv_nsec = self->nanoseconds;
ts->tv_sec = (time_t)dateTimeGetTimestamp(self);
}