2012-01-02 16 views
2

如何使用標準庫在C++中將字符串轉換爲日期和時間對象?如何將字符串轉換爲C++中的日期?

這裏是我的字符串

string input_time = "071215"; //071215 represents 7th December 2015 

的需求input_time要轉換爲Date對象,這樣我可以與Date對象進行比較。

bool dateExpired = (input_time < now); 
//where now is current date time 

if(dateExpired) printf("Expired"); 
else printf("Not expired"); 
+0

由於字符串的每個部分都是固定的(我猜),所以很容易提取相關數據並將其放入可用於獲取'time_t'的'struct tm'中。 – 2012-01-02 09:19:05

+3

語言環境也很重要。我住在哪裏意味着2007年12月15日。 – 2012-01-02 09:21:34

+0

您是否堅持使用該格式,或者您可以使用標準格式,例如http://en.wikipedia.org/wiki/ISO_8601? – juanchopanza 2012-01-02 09:23:41

回答

4

您可以使用c函數strptime。如果你想要一個C++的方式,你可以看看boost library

+0

我沒有訪問使用提升庫 – DreamCodeer 2012-01-02 09:19:45

+0

是的,只需使用strptime然後將結果轉換爲您需要的格式。我擔心你需要根據自己的語言環境檢查正確的格式(請參閱我的其他評論) – plaisthos 2012-01-02 09:44:01

0

如果你知道確切的格式,只需提取字段作爲子字符串,並運行它們通過istringstream將字符串更改爲數字。

#include <strstream> 

// . . . 

string dayString = input_time.substring(0, 2); 
istringstream iss(dayString); 
int day; 
iss >> day; 

// . . .