问题描述
我从服务器11/07/2020 10:57:13
获得了String,该服务器将其转换为双精度值1604723233
,但是转换后的双精度值比实际值小1小时。
下面是我尝试转换的方式...
double StringDatetoDouble(string &strDate,string format)
{
tm currentTime = CurrentTimetoTM();
tm timeinfo;
string strTimeZone = currentTime.tm_zone;
strDate.append("");
strDate.append(strTimeZone);
strptime(strDate.c_str(),format.c_str(),&timeinfo);
time_t timeInSec = mktime(&timeinfo);
return static_cast<double>(timeInSec);
}
tm CurrentTimetoTM()
{
struct tm timeinfo = {0};
time_t rawtime;
rawtime = time(&rawtime);
localtime_r(&rawtime,&timeinfo);
return timeinfo;
}
正确的方法是什么?这里有什么错过的吗?任何建议都值得赞赏。
解决方法
这是我建议的代码:
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
const int IST = (5 * 60 + 30) * 60; // GMT+05:30 (in s)
double StringDateToDouble(std::string &&strDate,std::string &&format = "%D %T") {
std::tm tm;
std::istringstream ss(strDate);
ss >> std::get_time(&tm,format.c_str());
return (std::mktime(&tm) - timezone) - IST;
}
int main() { std::cout << (long)StringDateToDouble("11/07/2020 12:59:22"); }
参考:
如第二篇参考文献所述,std::mktime(&tm) - timezone
将在格林尼治标准时间给予时间。现在,由于您的服务器正在IST中发送响应,因此您需要手动从中减去响应,以获取自大纪元以来的时间。
请注意,C ++标准不能保证1970-01-01T00:00Z
是std::time_t(0)
。
引用std::time
:
未指定std :: time_t中日历时间的编码,但是大多数系统符合POSIX规范,并返回一个整数类型的值,该值保持距大纪元以来的秒数。 std :: time_t是32位有符号整数的实现(许多历史实现)在2038年失败。
有关更多讨论,请参考参考文献3中提到的线程。