xs_time.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* copyright (c) 2022 grunfink - MIT license */
  2. #ifndef _XS_TIME_H
  3. #define _XS_TIME_H
  4. #include <time.h>
  5. d_char *xs_str_time(time_t t, const char *fmt, int local);
  6. #define xs_str_localtime(t, fmt) xs_str_time(t, fmt, 1)
  7. #define xs_str_utctime(t, fmt) xs_str_time(t, fmt, 0)
  8. time_t xs_parse_time(const char *str, const char *fmt, int local);
  9. #define xs_parse_localtime(str, fmt) xs_parse_time(str, fmt, 1)
  10. #define xs_parse_utctime(str, fmt) xs_parse_time(str, fmt, 0)
  11. #ifdef XS_IMPLEMENTATION
  12. d_char *xs_str_time(time_t t, const char *fmt, int local)
  13. /* returns a d_char with a formated time */
  14. {
  15. struct tm tm;
  16. char tmp[64];
  17. if (t == 0)
  18. t = time(NULL);
  19. if (local)
  20. localtime_r(&t, &tm);
  21. else
  22. gmtime_r(&t, &tm);
  23. strftime(tmp, sizeof(tmp), fmt, &tm);
  24. // printf("%d %d\n", local, t - xs_parse_time(tmp, fmt, local));
  25. return xs_str_new(tmp);
  26. }
  27. char *strptime(const char *s, const char *format, struct tm *tm);
  28. time_t xs_parse_time(const char *str, const char *fmt, int local)
  29. {
  30. struct tm tm;
  31. memset(&tm, '\0', sizeof(tm));
  32. strptime(str, fmt, &tm);
  33. /* try to guess the Daylight Saving Time */
  34. if (local)
  35. tm.tm_isdst = -1;
  36. return local ? mktime(&tm) : timegm(&tm);
  37. }
  38. #endif /* XS_IMPLEMENTATION */
  39. #endif /* _XS_TIME_H */