1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "utils_datetime.h"
17
18 #include <time.h>
19
20 #ifdef __cplusplus
21 extern "C" {
22 #endif
23
24 #define SEC_TO_NANOSEC 1000000000
25 #define SEC_TO_MICROSEC 1000000
26 #define SEC_TO_MILLISEC 1000
27 #define MILLISEC_TO_NANOSEC 1000000
28 #define MILLISEC_TO_USEC 1000
29 #define MICROSEC_TO_NANOSEC 1000
30
GetMillisecondSinceBoot(void)31 uint64_t GetMillisecondSinceBoot(void)
32 {
33 struct timespec ts;
34 clock_gettime(CLOCK_BOOTTIME, &ts);
35 return (ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC);
36 }
37
GetMillisecondSince1970(void)38 uint64_t GetMillisecondSince1970(void)
39 {
40 struct timespec ts;
41 clock_gettime(CLOCK_REALTIME, &ts);
42 return ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC;
43 }
44
GetDateTimeByMillisecondSince1970(uint64_t input,DateTime * datetime)45 bool GetDateTimeByMillisecondSince1970(uint64_t input, DateTime *datetime)
46 {
47 if (datetime == NULL) {
48 return false;
49 }
50 struct tm tm;
51 time_t time = (time_t)(input / SEC_TO_MILLISEC);
52 localtime_r(&time, &tm);
53
54 datetime->year = (uint16_t)(tm.tm_year + 1900); // need add 1900
55 datetime->mon = (uint16_t)(tm.tm_mon + 1);
56 datetime->day = (uint16_t)tm.tm_mday;
57 datetime->hour = (uint16_t)tm.tm_hour;
58 datetime->min = (uint16_t)tm.tm_min;
59 datetime->sec = (uint16_t)tm.tm_sec;
60 datetime->msec = (uint16_t)(input % SEC_TO_MILLISEC);
61 return true;
62 }
63
GetDateTimeByMillisecondSinceBoot(uint64_t input,DateTime * datetime)64 bool GetDateTimeByMillisecondSinceBoot(uint64_t input, DateTime *datetime)
65 {
66 if (datetime == NULL) {
67 return false;
68 }
69 static uint64_t compensate = 0;
70 if (compensate == 0) {
71 compensate = GetMillisecondSince1970() - GetMillisecondSinceBoot();
72 }
73
74 return GetDateTimeByMillisecondSince1970(input + compensate, datetime);
75 }
76 #ifdef __cplusplus
77 }
78 #endif