1 /* 2 * Copyright (c) 2024-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 16 #include "b_resources/b_constants.h" 17 #include "b_utils/b_time.h" 18 #include <chrono> 19 #include <iomanip> 20 #include <sstream> 21 #include <unistd.h> 22 23 namespace OHOS::FileManagement::Backup { GetTimeS()24int64_t TimeUtils::GetTimeS() 25 { 26 std::chrono::seconds nowS = std::chrono::duration_cast<std::chrono::seconds>( 27 std::chrono::system_clock::now().time_since_epoch()); 28 return nowS.count(); 29 } 30 GetTimeMS()31int64_t TimeUtils::GetTimeMS() 32 { 33 std::chrono::milliseconds nowMs = std::chrono::duration_cast<std::chrono::milliseconds>( 34 std::chrono::system_clock::now().time_since_epoch()); 35 return nowMs.count(); 36 } 37 GetTimeUS()38int64_t TimeUtils::GetTimeUS() 39 { 40 std::chrono::microseconds nowUs = std::chrono::duration_cast<std::chrono::microseconds>( 41 std::chrono::system_clock::now().time_since_epoch()); 42 return nowUs.count(); 43 } 44 GetSpendSecond(int64_t startTime)45uint32_t TimeUtils::GetSpendSecond(int64_t startTime) 46 { 47 if (startTime == 0) { 48 return 0; 49 } 50 int64_t endTime = GetTimeS(); 51 if (endTime < startTime) { 52 return 0; 53 } 54 return static_cast<uint32_t>(endTime - startTime); 55 } 56 GetSpendMS(int64_t startTime)57uint32_t TimeUtils::GetSpendMS(int64_t startTime) 58 { 59 if (startTime == 0) { 60 return 0; 61 } 62 int64_t endTime = GetTimeMS(); 63 if (endTime < startTime) { 64 return 0; 65 } 66 return static_cast<uint32_t>(endTime - startTime); 67 } 68 GetSpendUS(int64_t startTime)69uint64_t TimeUtils::GetSpendUS(int64_t startTime) 70 { 71 if (startTime == 0) { 72 return 0; 73 } 74 int64_t endTime = GetTimeUS(); 75 if (endTime < startTime) { 76 return 0; 77 } 78 return endTime - startTime; 79 } 80 GetCurrentTime()81std::string TimeUtils::GetCurrentTime() 82 { 83 auto now = std::chrono::system_clock::now(); 84 auto time = std::chrono::system_clock::to_time_t(now); 85 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()); 86 std::stringstream strTime; 87 strTime << (std::put_time(std::localtime(&time), "%Y-%m-%d %H:%M:%S:")) << (std::setfill('0')) 88 << (std::setw(BConstants::INDEX)) << (ms.count() % BConstants::MS_1000); 89 return strTime.str(); 90 } 91 } // namespace OHOS::FileManagement::Backup