[英]C++ - compare two dates
我正在編寫一個需要比較兩個日期的應用程序。 這是我到目前為止的內容:
struct entry {
string text;
string date; // format: dd.mm.yyyy
bool finished;
};
string addNulls(int number, int cols) {
string num = to_string(number);
if (num.size() < cols) {
int count = cols - num.size();
for (int i = 0; i < count; i++) {
num = "0" + num;
}
}
return num;
}
// [...]
entry e = {"here is some text", "21.03.2019", false};
int day2 = atoi(e.date.substr(0, 2).c_str());
int month2 = atoi(e.date.substr(3, 2).c_str());
int year2 = atoi(e.date.substr(6, 4).c_str());
time_t t = time(0);
struct tm * now = localtime(&t);
string date1 = e.date.substr(6, 4) + "-" + e.date.substr(3, 2) + "-" + e.date.substr(0, 2) + " 00:00:00";
string date2 = addNulls(now->tm_year, 4) + "-" + addNulls(now->tm_mon, 2) + "-" + addNulls(now->tm_mday, 2) + " 00:00:00";
if(date2 > date1) {
// do something
}
該代碼將獲得一個包含日期的“ entry”結構。 比代碼將日期與實際時間進行比較。 問題是,它不起作用! 我使用一些示例內容運行了一些測試,但是結果(date2> date1)返回false。
為什么?
我讀的是: C ++與字符串日期比較
我實際上沒有回答你的問題。 但是,我為您提供解決方案。 您是否考慮過日期/時間庫? 提高日期時間很受歡迎。
如果您使用C ++ 11或更高版本進行編譯,則建議您使用此日期時間庫 ,因為它僅用於標頭(消除了鏈接到boost等庫的需要),並且我認為它的語法更簡潔(是一個非常主觀和偏頗的觀點)。
后一個庫建立在C ++ 11 <chrono>
庫上。 這是使用此庫的示例代碼:
#include "date.h"
#include <iostream>
#include <string>
struct entry {
std::string text;
date::year_month_day date;
bool finished;
};
int
main()
{
entry e = {"here is some text", date::day(21)/3/2019, false};
auto day2 = e.date.day();
auto month2 = e.date.month();
auto year2 = e.date.year();
auto t = std::chrono::system_clock::now();
auto date1 = date::sys_days{e.date};
auto date2 = t;
if (date2 > date1)
std::cout << "It is past " << e.date << '\n';
else
std::cout << "It is not past " << e.date << '\n';
}
當前輸出:
It is not past 2019-03-21
在C ++ 14中,chrono文字使指定文字時間非常緊湊:
using namespace std::literals;
auto date1 = date::sys_days{e.date} + 0h + 0min + 0s;
同樣在文字方面,如果您using namespace date;
則可以使entry
的結構稍微緊湊一些using namespace date;
:
entry e = {"here is some text", 21_d/3/2019, false};
重用日期或日期時間類,甚至創建自己的類比嘗試使用字符串保存日期要容易。 此外,當您打算將持續時間添加到某個時間點時,還可以避免在日期中意外添加字符串的類型安全性。
為什么不使用strptime
來解析日期字符串,將其轉換為紀元時間然后進行比較?
#include <time.h>
char *
strptime(const char *restrict buf, const char *restrict format,
struct tm *restrict tm);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.