• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2024 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 #include "time_util.h"
16 
17 #include <chrono>
18 #include <ctime>
19 #include <sys/time.h>
20 
21 namespace OHOS {
22 namespace HiviewDFX {
23 namespace TimeUtil {
24 namespace {
25 const std::string DEFAULT_DATE = "19700101";
26 }
GetMilliseconds()27 uint64_t GetMilliseconds()
28 {
29     auto now = std::chrono::system_clock::now();
30     auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
31     return millisecs.count();
32 }
33 
GetDate()34 std::string GetDate()
35 {
36     time_t nowTime = time(nullptr);
37     if (nowTime < 0) {
38         return DEFAULT_DATE;
39     }
40     char dateChs[9] = { 0 }; // 9 means 8(19700101) + 1('\0')
41     struct tm localTm;
42     if (localtime_noenv_r(&nowTime, &localTm) == nullptr) {
43         return DEFAULT_DATE;
44     }
45     if (strftime(dateChs, sizeof(dateChs), "%Y%m%d", &localTm) == 0) {
46         return DEFAULT_DATE;
47     }
48     return dateChs;
49 }
50 
GetTimeZone()51 std::string GetTimeZone()
52 {
53     struct timeval tv;
54     if (gettimeofday(&tv, nullptr) != 0) {
55         return "";
56     }
57     time_t sysSec = tv.tv_sec;
58     struct tm tmLocal;
59     if (localtime_noenv_r(&sysSec, &tmLocal) == nullptr) {
60         return "";
61     }
62     constexpr size_t buffSize = 6; // for '+0800\0'
63     char buff[buffSize] = {0};
64     if (strftime(buff, sizeof(buff) - 1, "%z", &tmLocal) == 0) {
65         return "";
66     }
67     return std::string(buff);
68 }
69 
GetMilliSecondsTimestamp(clockid_t clockId)70 int64_t GetMilliSecondsTimestamp(clockid_t clockId)
71 {
72     struct timespec times {};
73     if (clock_gettime(clockId, &times) == -1) {
74         return -1;
75     }
76     constexpr int64_t secondToMillisecond = 1 * 1000;
77     constexpr int64_t nanosecondToMillisecond = 1 * 1000 * 1000;
78     return times.tv_sec * secondToMillisecond + times.tv_nsec / nanosecondToMillisecond;
79 }
80 
GetElapsedMilliSecondsSinceBoot()81 int64_t GetElapsedMilliSecondsSinceBoot()
82 {
83     return GetMilliSecondsTimestamp(CLOCK_BOOTTIME);
84 }
85 } // namespace TimeUtil
86 } // namespace HiviewDFX
87 } // namespace OHOS
88