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 #ifndef OHOS_ABILITY_RUNTIME_TIME_UTIL_H 17 #define OHOS_ABILITY_RUNTIME_TIME_UTIL_H 18 19 #include <cinttypes> 20 #include <sys/stat.h> 21 #include <time.h> 22 23 namespace OHOS::AbilityRuntime { 24 namespace TimeUtil { 25 // NANOSECONDS mean 10^9 nano second 26 constexpr int64_t NANOSECONDS = 1000000000; 27 // MICROSECONDS mean 10^6 milli second 28 constexpr int64_t MICROSECONDS = 1000000; 29 constexpr int64_t SEC_TO_MILLISEC = 1000; 30 constexpr int64_t MAX_TIME_BUFF = 64; // 64 : for example 2021-05-27-01-01-01 31 SystemTimeMillisecond()32[[maybe_unused]] static int64_t SystemTimeMillisecond() 33 { 34 struct timespec t; 35 t.tv_sec = 0; 36 t.tv_nsec = 0; 37 clock_gettime(CLOCK_MONOTONIC, &t); 38 return (int64_t)((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS; 39 } 40 FormatTime(const std::string & format)41[[maybe_unused]] static std::string FormatTime(const std::string &format) 42 { 43 auto now = std::chrono::system_clock::now(); 44 auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()); 45 auto timestamp = millisecs.count(); 46 std::time_t tt = static_cast<std::time_t>(timestamp / SEC_TO_MILLISEC); 47 std::tm t = *std::localtime(&tt); 48 char buffer[MAX_TIME_BUFF] = {0}; 49 std::strftime(buffer, sizeof(buffer), format.c_str(), &t); 50 return std::string(buffer); 51 } 52 } // namespace TimeUtil 53 } // namespace OHOS::AbilityRuntime 54 #endif // OHOS_ABILITY_RUNTIME_TIME_UTIL_H