[英]String to date not working in C++ when using the %d%m%y format to create am std::time_t
[英]How to convert a "%Y%m%d" format string into a time_t variable in C++?
我正在嘗試將字符串轉換為 time_t 變量。 這是我試過的代碼:
#include "pch.h"
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
using namespace std;
time_t String_to_timet1(string endDate) {
tm tm = { 0 };
stringstream ss(endDate);
ss >> get_time(&tm, "%Y-%m-%d %H:%M:%S");
time_t epoch = mktime(&tm);
return epoch;
}
time_t String_to_timet2(string endDate) {
tm tm = { 0 };
stringstream ss(endDate);
ss >> get_time(&tm, "%Y%m%d");
time_t epoch = mktime(&tm);
return epoch;
}
int main()
{
time_t time_certainTime1 = String_to_timet1("2019-01-01 00:00:00");
cout << time_certainTime1 << endl;
time_t time_certainTime2 = String_to_timet2("20190101");
cout << time_certainTime2 << endl;
return 0;
}
我預計結果會相同,但是當我使用 Visual Studio 2017 運行代碼時,結果是:
1546268400
-1
當我在https://www.onlinegdb.com/online_c++_compiler上運行相同的代碼時,結果是:
1546300800
1546300800
問題:為什么 Visual Studio 在獲得“%Y%m%d”類型的字符串時給我 -1(當在線編譯器給我預期的結果時)? 如何使用這種格式制作 time_t 變量?
在 %m 和 %d 的文檔中,它表示允許但不需要前導零。 這意味着它實際上沒有指定是否可以在沒有分隔符的情況下工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.