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
16 #include "iam_time.h"
17
18 #include <chrono>
19 #include <cstdint>
20 #include <ctime>
21 #include <string>
22 #include <sys/types.h>
23
24 #include "securec.h"
25
26 namespace OHOS {
27 namespace UserIam {
28 namespace Common {
GetNowTimeString()29 const std::string GetNowTimeString()
30 {
31 using namespace std::chrono;
32 constexpr uint32_t buffSize = 64;
33 constexpr uint32_t dataLen = 19;
34 constexpr uint32_t startYear = 1900;
35 const time_point<system_clock> now = system_clock::now();
36 time_t tt = system_clock::to_time_t(now);
37 struct tm curr;
38 char timeStr[buffSize + 1] = {0};
39 localtime_r(&tt, &curr);
40 int32_t len = snprintf_s(timeStr, sizeof(timeStr), dataLen, "%04u-%02d-%02d %02d:%02d:%02d",
41 curr.tm_year + startYear, curr.tm_mon + 1, curr.tm_mday, curr.tm_hour, curr.tm_min, curr.tm_sec);
42 if (len < 0) {
43 return std::string();
44 }
45 return std::string(timeStr);
46 }
47 } // namespace Common
48 } // namespace UserIam
49 } // namespace OHOS