如何处理C++的时间

How to deal with time in C++

本文关键字:C++ 时间 处理 何处理      更新时间:2023-10-16

我有一个关于在 c++ 中管理日期和时间的问题。我的课程中有两个课程飞机和飞行。

"我的飞机"将包含以下数据:

string tailNumber;//Plane's unique trait
vector<vector<string>> planeSchedule;//2D string vector to contain plane's depature date and arrival date

我的飞行舱类将包含以下数据:

string tailNumber;//Plane's unique trait
string departureDate;
string arrivalDate;

在我的主课中,我将输入出发日期和到达日期的值,格式为:"YYYY/MM/DD HH:MM",例如:"2019/04/15 10:30" and "2019/04/16 9:30"(我将使用 24 小时格式,时间将是格林威治标准时间)。

我的问题是如何将上面的两个字符串转换为适当的格式以存储在我的planeSchedule中,以便我能够避免planeSchedule中的时间冲突。

例如,如果下次我添加航班的出发和到达日期为:2019/04/15 10:30" and "2019/04/16 9:30"例如:"2019/04/15 13:30" and "2019/04/16 7:30",我将收到类似"航班冲突,飞机不可用"之类的错误。

我的教授建议使用无符号的 long int 来存储时间,但我真的不知道从哪里开始解决这个问题。任何帮助/建议将不胜感激。

关于C++日期和时间的首选位置是<chrono>。其中一些自C++11以来一直伴随着我们,其中一些我们将在C++20中看到。它与<ctime>中的 C 样式日期和时间实用程序结合使用,这甚至可能足以满足您的目的。

尝试将日期/时间处理为整数或字符串,从输入中解析它们,比较并将它们转换为字符串以进行输出,将有效地导致您重新实现这些标头中已有的部分内容(又名"重新发明轮子")。

根据对系统表现不佳的长期经验,我有两条建议:-)

首先是不要将日期和时间信息存储为字符串或整数值,尤其是当C++在std::chrono中对此有很好的支持时。如果使用正确的类型,比较和操作将变得相对简单。

其次,确保始终使用 UTC。获取本地时间后,应尽快将其转换为 UTC,并在呈现时尽可能晚地转换回本地时间。这也将大大简化比较。


举个例子,这里有一个完整的程序,它显示了操作中的简单性(a):

#include <iostream>
#include <iomanip>
#include <sstream>
#include <chrono>
using std::chrono::system_clock;
using std::chrono::duration_cast;
namespace {
system_clock::time_point getTimePoint(std::string strTime) {
std::tm myTm = {};
std::stringstream ss(strTime.c_str());
ss >> std::get_time(&myTm, "%Y/%m/%d %H:%M");
return system_clock::from_time_t(std::mktime(&myTm));
}

void outputTime(const char *desc, system_clock::time_point &tp) {
std::time_t now = system_clock::to_time_t(tp);
std::cout << desc
<< std::put_time(std::localtime(&now), "%Y-%m-%d %H:%M") << "n";
}
}
int main() {
std::string startTime = "2019/04/15 10:30";
std::string endTime   = "2019/04/16 09:30";
auto startTp = getTimePoint(startTime);
auto endTp = getTimePoint(endTime);
outputTime("Start time: ", startTp);
outputTime("  End time: ", endTp);
auto duration = duration_cast<std::chrono::minutes>(endTp - startTp);
std::cout << "nThere are " << duration.count() << " minutes between "
<< startTime << " and " << endTime << "n";
}

该程序的输出为:

Start time: 2019-04-15 10:30
End time: 2019-04-16 09:30
There are 1380 minutes between 2019/04/15 10:30 and 2019/04/16 09:30

(a)是的,该程序可能看起来相当大,但这只是因为使它成为一个完整程序的东西。getTimePointoutputTime函数显示了如何与时间点进行转换,简单性的实质是包含duration_cast的行,以获取两个时间点之间的分钟数。