1 /*
2 * Copyright (c) 2023 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 "TimeTool.h"
17
18 #include <chrono>
19 #include <iostream>
20
21 #include "LocalDate.h"
22
23 using namespace std;
24
GetFormatTime()25 string TimeTool::GetFormatTime()
26 {
27 string timeNow = FormateTimeNow();
28 string formatTime = "[" + timeNow + "]";
29 return formatTime;
30 }
31
GetTraceFormatTime()32 string TimeTool::GetTraceFormatTime()
33 {
34 string traceTimeNow = FormateTimeNow();
35 return traceTimeNow;
36 }
37
FormateTimeNow()38 string TimeTool::FormateTimeNow()
39 {
40 pair<tm, int64_t> timePair = GetCurrentTime();
41 struct tm utcTime = timePair.first;
42 int64_t msTime = timePair.second;
43 string now = FixedTime(utcTime.tm_year + 1900, 4) // year need add 1900,year width is 4
44 + "-" + FixedTime(utcTime.tm_mon + 1, 2) // month need add 1,month width is 2
45 + "-" + FixedTime(utcTime.tm_mday, 2) // day width is 2
46 + "T" + FixedTime(utcTime.tm_hour, 2) // hours width is 2
47 + ":" + FixedTime(utcTime.tm_min, 2) // mins width is 2
48 + ":" + FixedTime(utcTime.tm_sec, 2) // sec width is 2
49 + "." + FixedTime(msTime % 1000, 3); // ms width is 3;Moduloon 1000 is to get milliseconds.
50 return now;
51 }
52
FixedTime(int32_t time,int32_t width)53 string TimeTool::FixedTime(int32_t time, int32_t width)
54 {
55 string tm = to_string(time);
56 int len = tm.length();
57 if (len < width) {
58 for (int i = 0; i < width - len; i++) {
59 tm = "0" + tm;
60 }
61 }
62 return tm;
63 }
64
GetCurrentTime()65 pair<tm, int64_t> TimeTool::GetCurrentTime()
66 {
67 const std::time_t e8zone = 8 * 60 * 60 * 1000; // Time offset of GMT+08:00, in milliseconds, 8h*60m*60s*1000ms
68 std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
69 std::chrono::milliseconds millsec = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
70 std::time_t ms = millsec.count() + e8zone;
71 millsec = std::chrono::milliseconds(ms);
72 now = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(millsec);
73 auto time = std::chrono::system_clock::to_time_t(now);
74 struct tm utcTime;
75 LocalDate::GmTimeSafe(utcTime, time);
76 pair<tm, int64_t> timePair = make_pair(utcTime, ms);
77 return timePair;
78 }
79