#include <iostream>
#include <string>
#include <curl/curl.h>
#include <ctime>
#include <iomanip>
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* output) {
size_t totalSize = size * nmemb;
output->append(static_cast<char*>(contents), totalSize);
return totalSize;
}
// 将日期字符串转换为指定格式
std::string formatDateString(const std::string& dateString) {
std::tm t;
std::istringstream iss(dateString);
// 解析日期字符串
iss >> std::get_time(&t, "%a, %d %b %Y %H:%M:%S %Z");
if (iss.fail()) {
return "";
}
std::ostringstream oss;
// 格式化日期
oss << std::put_time(&t, "%m%d%H%M%Y.%S");
return oss.str();
}
int main() {
CURL* curl;
CURLcode res;
std::string responseHeaders;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://your-backend-server/current-time");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &responseHeaders);
curl_easy_setopt(curl, CURLOPT_HEADER, 1L);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "Failed to perform request: " << curl_easy_strerror(res) << std::endl;
} else {
std::string dateHeader = "Date: ";
size_t startPos = responseHeaders.find(dateHeader);
if (startPos != std::string::npos) {
startPos += dateHeader.length();
size_t endPos = responseHeaders.find("\r
", startPos);
std::string dateString = responseHeaders.substr(startPos, endPos - startPos);
std::string formattedDate = formatDateString(dateString);
if (!formattedDate.empty()) {
std::cout << "Formatted date: " << formattedDate << std::endl;
} else {
std::cerr << "Failed to format date string." << std::endl;
}
} else {
std::cerr << "Failed to extract server time from response headers." << std::endl;
}
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
formatdatestring方法会将时间格式化为指定的格式,但是如果头部信息返回的时间如果不是北京时间,则可以修改方法修改为北京时间,如下:
// 将日期字符串转换为指定格式(北京时间)
std::string formatDateString(const std::string& dateString) {
std::tm t;
std::istringstream iss(dateString);
// 解析日期字符串
iss >> std::get_time(&t, "%a, %d %b %Y %H:%M:%S %Z");
if (iss.fail()) {
return "";
}
// 将 tm 结构转换为系统时钟的时间点
std::chrono::system_clock::time_point tp = std::chrono::system_clock::from_time_t(std::mktime(&t));
// 将时间点转换为北京时间
std::chrono::hours offset(8); // 北京时间偏移量为+8小时
tp += offset;
// 转换为本地时间
std::time_t tt = std::chrono::system_clock::to_time_t(tp);
t = *std::localtime(&tt);
std::ostringstream oss;
// 格式化日期
oss << std::put_time(&t, "%m%d%H%M%Y.%S");
return oss.str();
}
int main() {
// ...
}