1 /* 2 * Copyright (c) 2022 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 #include "time_util.h" 16 17 #include <chrono> 18 #include <ctime> 19 #include <sys/time.h> 20 21 namespace OHOS { 22 namespace HiviewDFX { 23 namespace TimeUtil { 24 namespace { 25 const std::string DEFAULT_DATE = "19700101"; 26 } GetMilliseconds()27uint64_t GetMilliseconds() 28 { 29 auto now = std::chrono::system_clock::now(); 30 auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()); 31 return millisecs.count(); 32 } 33 GetDate()34std::string GetDate() 35 { 36 time_t nowTime = time(nullptr); 37 if (nowTime < 0) { 38 return DEFAULT_DATE; 39 } 40 char dateChs[9] = { 0 }; // 9 means 8(19700101) + 1('\0') 41 struct tm localTm; 42 if (localtime_r(&nowTime, &localTm) == nullptr) { 43 return DEFAULT_DATE; 44 } 45 if (strftime(dateChs, sizeof(dateChs), "%Y%m%d", &localTm) == 0) { 46 return DEFAULT_DATE; 47 } 48 return dateChs; 49 } 50 } // namespace TimeUtil 51 } // namespace HiviewDFX 52 } // namespace OHOS 53