1 /*
2 * Copyright (c) 2025 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 #define LOG_TAG "TimeUtils"
16
17 #include "time_utils.h"
18
19 #include <chrono>
20 #include <iomanip>
21 #include <sstream>
22
23 namespace OHOS {
24 namespace DistributedData {
25 constexpr int MAX_TIME_BUF_LEN = 32;
26 constexpr int MILLISECONDS_LEN = 3;
27 constexpr int NANO_TO_MILLI = 1000000;
28 constexpr int MILLI_PRE_SEC = 1000;
29
GetCurSysTimeWithMs()30 std::string TimeUtils::GetCurSysTimeWithMs()
31 {
32 auto now = std::chrono::system_clock::now();
33 std::time_t time = std::chrono::system_clock::to_time_t(now);
34 std::chrono::nanoseconds nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch());
35 return GetTimeWithMs(time, nsec.count());
36 }
37
GetTimeWithMs(time_t sec,int64_t nsec)38 std::string TimeUtils::GetTimeWithMs(time_t sec, int64_t nsec)
39 {
40 std::stringstream oss;
41 char buffer[MAX_TIME_BUF_LEN] = { 0 };
42 std::tm local_time;
43 localtime_r(&sec, &local_time);
44 std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &local_time);
45 oss << buffer << '.' << std::setfill('0') << std::setw(MILLISECONDS_LEN) << (nsec / NANO_TO_MILLI) % MILLI_PRE_SEC;
46 return oss.str();
47 }
48 } // namespace DistributedData
49 } // namespace OHOS
50