我正在尝试将2014-08-19T10:05:33Z转换为time_t。
我的代码结果为:1408435533
std::string expirationTime("2014-08-19T10:05:33Z");
struct tm tm;
memset(&tm, 0, sizeof(tm));
strptime(expirationTime.c_str(), "%Y-%m-%dT%TZ", &tm);
time_t timeStamp = mktime(&tm);
printf("time_t for %s is %ld \n\n", expirationTime.c_str(), timeStamp);
结果:
time_t for 2014-08-19T10:05:33Z is 1408435533
但是当我使用在线纪元转换器时,我得到以下内容:
1408435533
Is equivalent to:
08/19/2014 @ 8:05am (UTC)
2014-08-19T08:05:33+00:00 in ISO 8601
这似乎是错误的,因为有2小时的时差。
答案 0 :(得分:1)
使用Howard Hinnant's free, open-source, header-only, cross-platform, datetime library,你可以这样做:
#include "chrono_io.h"
#include "date.h"
#include <iostream>
#include <sstream>
int
main()
{
using namespace date;
std::string expirationTime("2014-08-19T10:05:33Z");
std::istringstream in{expirationTime};
sys_seconds timeStamp;
in >> parse("%Y-%m-%dT%TZ", timeStamp);
std::cout << "timeStamp is " << timeStamp.time_since_epoch()
<< " which is " << timeStamp << '\n';
}
这构建于C ++ 11引入的std::chrono
库之上。上述计划输出:
timeStamp is 1408442733s which is 2014-08-19 10:05:33
答案 1 :(得分:0)
见:http://man7.org/linux/man-pages/man3/timegm.3.html 使用timegm而不是mktime,但我认为它不适用于Windows