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 23namespace OHOS::AbilityRuntime { 24namespace TimeUtil { 25// NANOSECONDS mean 10^9 nano second 26constexpr int64_t NANOSECONDS = 1000000000; 27// MICROSECONDS mean 10^6 milli second 28constexpr int64_t MICROSECONDS = 1000000; 29constexpr int64_t SEC_TO_MILLISEC = 1000; 30constexpr int64_t MAX_TIME_BUFF = 64; // 64 : for example 2021-05-27-01-01-01 31constexpr int32_t DECIMAL_BASE = 10; 32 33[[maybe_unused]] static int64_t SystemTimeMillisecond() 34{ 35 struct timespec t; 36 t.tv_sec = 0; 37 t.tv_nsec = 0; 38 clock_gettime(CLOCK_MONOTONIC, &t); 39 return (int64_t)((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS; 40} 41 42[[maybe_unused]] static std::string FormatTime(const std::string &format) 43{ 44 auto now = std::chrono::system_clock::now(); 45 auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()); 46 auto timestamp = millisecs.count(); 47 std::time_t tt = static_cast<std::time_t>(timestamp / SEC_TO_MILLISEC); 48 std::tm t = *std::localtime(&tt); 49 char buffer[MAX_TIME_BUFF] = {0}; 50 std::strftime(buffer, sizeof(buffer), format.c_str(), &t); 51 return std::string(buffer); 52} 53 54[[maybe_unused]] static std::string DefaultCurrentTimeStr() 55{ 56 auto now = std::chrono::system_clock::now(); 57 auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()); 58 auto timestamp = millis.count(); 59 std::time_t tt = static_cast<std::time_t>(timestamp / SEC_TO_MILLISEC); 60 std::tm t{}; 61 localtime_r(&tt, &t); 62 char buffer[MAX_TIME_BUFF] = {0}; 63 std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &t); 64 auto remainder = timestamp % SEC_TO_MILLISEC; 65 std::string milliStr("000"); 66 for (int i = 2; i >= 0 && remainder > 0; i--) { 67 milliStr[i] = '0' + remainder % DECIMAL_BASE; 68 remainder /= DECIMAL_BASE; 69 } 70 return std::string(buffer) + "." + milliStr; 71} 72} // namespace TimeUtil 73} // namespace OHOS::AbilityRuntime 74#endif // OHOS_ABILITY_RUNTIME_TIME_UTIL_H