1 /*
2  * Copyright (C) 2015-2021 Alibaba Group Holding Limited
3  */
4 
5 #include <stdio.h>
6 #include <time.h>
7 
8 #include <k_api.h>
9 #include <aos/errno.h>
10 #include <aos/kernel.h>
11 
12 #include "rhino_p.h"
13 
14 #if (RHINO_CONFIG_KOBJ_DYN_ALLOC == 0)
15 #warning "RHINO_CONFIG_KOBJ_DYN_ALLOC is disabled!"
16 #endif
17 
18 static long long start_time_ms = 0;
19 
aos_calendar_time_set(uint64_t now_ms)20 void aos_calendar_time_set(uint64_t now_ms)
21 {
22     start_time_ms = now_ms - krhino_sys_time_get();
23 }
24 
aos_calendar_time_get(void)25 uint64_t aos_calendar_time_get(void)
26 {
27     return krhino_sys_time_get() + start_time_ms;
28 }
29 
aos_calendar_localtime_get(void)30 uint64_t aos_calendar_localtime_get(void)
31 {
32     if ((int64_t)(aos_calendar_time_get() - 8 * 3600 * 1000) < 0) {
33         return aos_calendar_time_get();
34     }
35     return aos_calendar_time_get() + 8 * 3600 * 1000;
36 }
37 
aos_now(void)38 uint64_t aos_now(void)
39 {
40     return krhino_sys_time_get() * 1000 * 1000;
41 }
42 
aos_now_ms(void)43 uint64_t aos_now_ms(void)
44 {
45     return krhino_sys_time_get();
46 }
47 
48 
aos_now_time_str(char * buffer,size_t len)49 aos_status_t aos_now_time_str(char *buffer, size_t len)
50 {
51 
52     uint64_t ms = aos_now_ms();
53 
54     if (buffer == NULL || len == 0) {
55         return -EINVAL;
56     }
57 
58     time_t actualTime = { ms / 1000 };
59     memset(buffer, 0, len);
60     strftime(buffer, len, "%m-%d %H:%M:%S", gmtime(&actualTime));
61     if ((int)(len - strlen(buffer) - 1) > 0) {
62         const int milli    = ms % 1000;
63         char      msStr[8] = {0};
64         snprintf(msStr, sizeof(msStr), ".%03d", milli);
65         strncat(buffer, msStr, len - strlen(buffer) - 1);
66     } else {
67         return -EINVAL;
68     }
69 
70     return 0;
71 }
72