fixed DateTime_get bugs and added FMT_DateTime

This commit is contained in:
Timerix 2025-11-18 16:00:50 +05:00
parent bc41577248
commit c68e4e87b3
2 changed files with 28 additions and 15 deletions

View File

@ -29,18 +29,18 @@ void sleepMsec(msec_t time);
typedef struct Time { typedef struct Time {
i32 nsec; i32 nsec; /* 0..999_999_999 */
i8 sec; i8 sec; /* 0..60 leap second??? */
i8 min; i8 min; /* 0..59 */
i8 hour; i8 hour; /* 0..23 */
} Time; } Time;
typedef struct Date { typedef struct Date {
i8 month_day; i8 month_day; /* 1..31 */
i8 month; i8 month; /* 1..12 */
i16 year; i16 year; /* 1900-xxxx */
i8 week_day; i8 week_day; /* 1..7 */
i16 year_day; i16 year_day; /* 1..366 */
} Date; } Date;
typedef struct DateTime { typedef struct DateTime {
@ -52,6 +52,19 @@ void DateTime_get(DateTime* dt, bool utc_time);
static inline void DateTime_getLocal(DateTime* dt) { DateTime_get(dt, false); } static inline void DateTime_getLocal(DateTime* dt) { DateTime_get(dt, false); }
static inline void DateTime_getUTC(DateTime* dt) { DateTime_get(dt, true); } static inline void DateTime_getUTC(DateTime* dt) { DateTime_get(dt, true); }
// yyyy.MM.dd_HH-mm-ss
#define FMT_DateTime_fileName "%04i.%02i.%02i_%02i-%02i-%02i"
// yyyy.MM.dd HH:mm:ss
#define FMT_DateTime_text "%04i.%02i.%02i %02i:%02i:%02i"
/*
USAGE:
DateTime dt;
DateTime_getLocal(&dt);
printf(FMT_DateTime_text, DT_expand(dt));
*/
#define DT_expand(dt) dt.d.year, dt.d.month, dt.d.month_day, dt.t.hour, dt.t.min, dt.t.sec
#if __cplusplus #if __cplusplus
} }
#endif #endif

View File

@ -51,21 +51,21 @@ void sleepMsec(msec_t time){
void DateTime_get(DateTime* dt, bool utc_time){ void DateTime_get(DateTime* dt, bool utc_time){
time_t c_time = time(NULL); time_t c_time = time(NULL);
struct tm c_tm; struct tm c_tm;
struct timespec c_timespec;
if(utc_time){ if(utc_time){
portable_gmtime_s(&c_time, &c_tm); portable_gmtime_s(&c_time, &c_tm);
} }
else { else {
portable_localtime_s(&c_time, &c_tm); portable_localtime_s(&c_time, &c_tm);
} }
struct timespec c_timespec;
clock_gettime(CLOCK_REALTIME, &c_timespec); clock_gettime(CLOCK_REALTIME, &c_timespec);
dt->t.nsec = c_timespec.tv_nsec; dt->t.nsec = c_timespec.tv_nsec;
dt->t.sec = c_timespec.tv_sec; dt->t.sec = c_tm.tm_sec;
dt->t.min = c_tm.tm_min; dt->t.min = c_tm.tm_min;
dt->t.hour = c_tm.tm_hour; dt->t.hour = c_tm.tm_hour;
dt->d.month_day = c_tm.tm_mday; dt->d.month_day = c_tm.tm_mday;
dt->d.month = c_tm.tm_mon; dt->d.month = c_tm.tm_mon + 1;
dt->d.year = c_tm.tm_year; dt->d.year = c_tm.tm_year + 1900;
dt->d.week_day = c_tm.tm_wday; dt->d.week_day = c_tm.tm_wday + 1;
dt->d.year_day = c_tm.tm_yday; dt->d.year_day = c_tm.tm_yday + 1;
} }