• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 {
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     auto tp = std::chrono::system_clock::from_time_t(std::mktime(&tm));
34 
35     auto tmp = std::chrono::duration_cast<std::chrono::seconds>(tp.time_since_epoch());
36     return tmp.count();
37 }
38 
GetNowTimeSeconds()39 time_t HttpTime::GetNowTimeSeconds()
40 {
41     auto now = std::chrono::system_clock::now();
42     return std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
43 }
44 
GetNowTimeGMT()45 std::string HttpTime::GetNowTimeGMT()
46 {
47     auto now = std::chrono::system_clock::now();
48     time_t timeSeconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
49     std::tm timeInfo = {0};
50 #ifdef WINDOWS_PLATFORM
51     if (gmtime_s(&timeInfo, &timeSeconds) == 0) {
52 #else
53     if (gmtime_r(&timeSeconds, &timeInfo) == nullptr) {
54 #endif
55         return {};
56     }
57     char s[MAX_TIME_LEN] = {0};
58     if (strftime(s, sizeof(s), GMT_TIME, &timeInfo) == 0) {
59         return {};
60     }
61     return s;
62 }
63 } // namespace OHOS::NetStack
64