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 "http_time.h"
17 
18 #include <chrono>
19 #include <ctime>
20 #include <iomanip>
21 #include <sstream>
22 
23 static constexpr const char *GMT_TIME = "%a, %d %b %Y %H:%M:%S GMT";
24 
25 static constexpr const int MAX_TIME_LEN = 128;
26 
27 namespace OHOS::NetStack::Http {
StrTimeToTimestamp(const std::string & time_str)28 time_t HttpTime::StrTimeToTimestamp(const std::string &time_str)
29 {
30     std::tm tm = {0};
31     std::stringstream ss(time_str);
32     ss >> std::get_time(&tm, GMT_TIME);
33 
34 #ifdef WINDOWS_PLATFORM
35     return _mkgmtime(&tm);
36 #else
37     return timegm(&tm);
38 #endif
39 }
40 
GetNowTimeSeconds()41 time_t HttpTime::GetNowTimeSeconds()
42 {
43     auto now = std::chrono::system_clock::now();
44     return std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
45 }
46 
GetNowTimeGMT()47 std::string HttpTime::GetNowTimeGMT()
48 {
49     auto now = std::chrono::system_clock::now();
50     time_t timeSeconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
51     std::tm timeInfo = {0};
52 #ifdef WINDOWS_PLATFORM
53     if (gmtime_s(&timeInfo, &timeSeconds) == 0) {
54 #else
55     if (gmtime_r(&timeSeconds, &timeInfo) == nullptr) {
56 #endif
57         return {};
58     }
59     char s[MAX_TIME_LEN] = {0};
60     if (strftime(s, sizeof(s), GMT_TIME, &timeInfo) == 0) {
61         return {};
62     }
63     return s;
64 }
65 } // namespace OHOS::NetStack::Http
66