From 43ab1674e876eafbd1dfcc4b5b07c1b6ab18b94d Mon Sep 17 00:00:00 2001 From: kamkow1 Date: Thu, 16 Oct 2025 15:46:06 +0200 Subject: [PATCH] ulib More time conversion utils --- ulib/time/time.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++++ ulib/time/time.h | 2 ++ 2 files changed, 61 insertions(+) diff --git a/ulib/time/time.c b/ulib/time/time.c index 977ce92..635a8fc 100644 --- a/ulib/time/time.c +++ b/ulib/time/time.c @@ -29,3 +29,62 @@ timeunix_t time_tounix(Time *time) { secs += time->second; return secs; } + +void timeunix_totime(timeunix_t unix, Time *time) { + uint64_t days = unix / 86400; + uint32_t rem = days % 86400; + + time->hour = rem / 3600; + time->minute = (rem % 3600) / 60; + time->second = rem % 60; + + uint32_t year = 1970; + for (;;) { + uint32_t ydays = time_isleap(year) ? 366 : 365; + if (days >= ydays) { + days -= ydays; + year++; + } else { + break; + } + } + time->year = year; + + bool leap = time_isleap(year); + uint32_t month = 0; + while (month < 11) { + uint32_t next = days_before_month[month + 1]; + if (leap && month + 1 > 1) { + next++; + } + if (days < next) { + break; + } + month++; + } + + uint32_t month_start = days_before_month[month]; + if (leap && month > 1) { + month_start++; + } + + time->month = month + 1; + time->day = (days - month_start) + 1; +} + +uint32_t time_totalhours(Time *time) { + uint32_t days = 0; + for (uint32_t y = 1970; y < time->year; y++) { + days += time_isleap(y) ? 366 : 365; + } + + days += days_before_month[time->month - 1]; + if (time->month > 2 && time_isleap(time->year)) { + days += 1; + } + + days += (time->day - 1); + + uint32_t total = days * 24 + time->hour; + return total; +} diff --git a/ulib/time/time.h b/ulib/time/time.h index 8fc9f7e..e590435 100644 --- a/ulib/time/time.h +++ b/ulib/time/time.h @@ -4,5 +4,7 @@ #include timeunix_t time_tounix(Time *time); +void timeunix_totime(timeunix_t unix, Time *time); +uint32_t time_totalhours(Time *time); #endif // ULIB_TIME_TIME_H_