gtime.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "gtime.h"
  2. #include <time.h>
  3. #include "os/co_task.h"
  4. //one while will use 4 ins
  5. /* below function is dumy here, will overide by xxx_rtc.c */
  6. __weak void rtc_set_time_with_utc_second(uint32_t s){
  7. }
  8. __weak uint32_t rtc_get_timestamp(void){
  9. return 0;
  10. }
  11. /* set rtc time, used utc timestamp, can not include time zone*/
  12. uint32_t calendar_to_utc(time_val *time){
  13. struct tm utc_time;
  14. struct tm my_time;
  15. memset(&utc_time, 0, sizeof (struct tm));
  16. memset(&my_time, 0, sizeof (struct tm));
  17. my_time.tm_mday = time->day;
  18. my_time.tm_mon = time->month- 1;
  19. my_time.tm_year = time->year - 1900;
  20. my_time.tm_hour = time->hour;
  21. my_time.tm_min = time->minute;
  22. my_time.tm_sec = time->second;
  23. utc_time.tm_mday = 1;
  24. utc_time.tm_mon = 1 - 1;
  25. utc_time.tm_year = 1970 - 1900;
  26. utc_time.tm_hour = 0;
  27. utc_time.tm_min = 0;
  28. utc_time.tm_sec = 0;
  29. return mktime(&my_time) - mktime(&utc_time);
  30. }
  31. void set_utc_time(time_val *time){
  32. uint32_t second = calendar_to_utc(time);
  33. rtc_set_time_with_utc_second(second);
  34. }
  35. /* get the utc readable time */
  36. void utc_to_calendar(uint32_t second, time_val *out){
  37. struct tm *tm;
  38. tm = localtime((time_t *)&second);
  39. out->year = tm->tm_year + 1900;
  40. out->month = tm->tm_mon + 1;
  41. out->day = tm->tm_mday;
  42. out->hour = tm->tm_hour;
  43. out->minute = tm->tm_min;
  44. out->second = tm->tm_sec;
  45. }
  46. /*tz quarter-hour ,15min ,-48~+48*/
  47. uint32_t get_timestamp_with_time_zone(int8_t tz){
  48. return (rtc_get_timestamp()+ tz*15*60);
  49. }
  50. uint32_t get_timestamp(void){
  51. return rtc_get_timestamp();
  52. }
  53. void get_local_time(time_val *out, int8_t tz){
  54. utc_to_calendar(get_timestamp_with_time_zone(tz), out);
  55. }