【发布时间】:2017-10-19 09:56:27
【问题描述】:
假设我从 Web 服务器接收到一个要解析的字符串。此字符串包含格式为YYYY-MM-DD 的日期。
我想要的是将它转换为代表当天开始的时间戳,因此我不想要秒、分钟和小时。
作为一个虚拟示例,我试图提取当天的时间戳,一旦转换为YYYY-MM-DD 格式。代码如下:
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>
int main()
{
// Current time at GMT
std::time_t now = std::time(0);
std::tm *now_tm = std::gmtime(&now);
std::ostringstream oss;
// Extract yyyy-mm-dd = %F
oss << std::put_time(now_tm, "%F");
// Use oss to get a date without seconds from
// current time at gmt
std::tm tm;
std::istringstream ss(oss.str());
ss >> std::get_time(&tm, "%F");
std::time_t current_date = std::mktime(&tm);
std::cout << oss.str() << std::endl;
std::cout << "cd: " << current_date << std::endl;
return 0;
}
输出是:
2017-10-19
cd: 1908337984324104
提取的时间戳显然是错误的。使用%F格式解析2017-10-19字符串的问题在哪里?
【问题讨论】: