• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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 TELEPHONY_TIME_UTIL_H
17 #define TELEPHONY_TIME_UTIL_H
18 
19 #include <ctime>
20 #include <cstring>
21 
22 namespace OHOS {
23 namespace Telephony {
FormatDate(std::string & date,const tm * ltm)24 void FormatDate(std::string &date, const tm *ltm)
25 {
26     if (ltm != nullptr) {
27         int START_YEAR = 1900;
28         int DOUBLE_DIGIT = 10;
29         int year = START_YEAR + ltm->tm_year;
30         int month = 1 + ltm->tm_mon;
31         int day = ltm->tm_mday;
32         int hour = ltm->tm_hour;
33         int minute = ltm->tm_min;
34         int second = ltm->tm_sec;
35         date.append(std::to_string(year));
36         date.append("-");
37         if (month < DOUBLE_DIGIT) {
38             date.append("0");
39         }
40         date.append(std::to_string(month));
41         date.append("-");
42         if (day < DOUBLE_DIGIT) {
43             date.append("0");
44         }
45         date.append(std::to_string(day));
46         date.append(" ");
47         if (hour < DOUBLE_DIGIT) {
48             date.append("0");
49         }
50         date.append(std::to_string(hour));
51         date.append(":");
52         if (minute < DOUBLE_DIGIT) {
53             date.append("0");
54         }
55         date.append(std::to_string(minute));
56         date.append(":");
57         if (second < DOUBLE_DIGIT) {
58             date.append("0");
59         }
60         date.append(std::to_string(second));
61     }
62 }
63 
GetCurrentTime(std::string & date)64 void GetCurrentTime(std::string &date)
65 {
66     time_t *DEFAULT_TIMER = 0;
67     time_t now = time(DEFAULT_TIMER);
68     if (now == -1) {
69         return;
70     }
71     struct tm tm = { 0 };
72     struct tm *ltm = localtime_r(&now, &tm);
73     if (ltm == nullptr) {
74         return;
75     }
76     FormatDate(date, ltm);
77 }
78 
GetTimeOfThirty(std::string & date)79 void GetTimeOfThirty(std::string &date)
80 {
81     int64_t THIRTY_DAYS = 2592000;
82     time_t *DEFAULT_TIMER = 0;
83     time_t now = time(DEFAULT_TIMER) - THIRTY_DAYS;
84     date = std::to_string(now);
85 }
86 } // namespace Telephony
87 } // namespace OHOS
88 #endif // TELEPHONY_TIME_UTIL_H
89