[英]How to Convert String date to double in C++,
我從服務器11/07/2020 10:57:13
獲取 String ,我將其轉換為 double 值1604723233
,但是轉換后的 double 值比實際值小 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 中發送響應,您需要手動從中減去它以獲得自 Epoch 以來的時間。
請注意,C++ 標准不保證1970-01-01T00:00Z
是std::time_t(0)
。
引用std::time
:
std::time_t 中日歷時間的編碼未指定,但大多數系統符合 POSIX 規范並返回一個整數類型的值,該值包含自 Epoch 以來的秒數。 std::time_t 是 32 位有符號整數的實現(許多歷史實現)在 2038 年失敗。
有關更多討論,請參閱參考文獻 3 中提到的線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.