如何处理C++的时间
How to deal with time in C++
我有一个关于在 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)是的,该程序可能看起来相当大,但这只是因为使它成为一个完整程序的东西。getTimePoint
和outputTime
函数显示了如何与时间点进行转换,简单性的实质是包含duration_cast
的行,以获取两个时间点之间的分钟数。
- C++为构建时间获取QDateTime的可靠方法
- 从持续时间构造std::chrono::system_clock::time_point
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 使用简单类型列表实现的指数编译时间.为什么
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在已经使用Git的情况下减少编译时间
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 从文本文件中读取时钟时间和事件时间并进行处理
- 具有未知值时的时间复杂性
- 如何减少花费的时间
- C++在变量给定的指定时间内关闭电脑
- rcpp函数中的清理时间很长
- C++:floor unix时间戳到UTC月份
- 如何在c++中录制具有精确帧时间戳的视频
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- KMP算法和LPS表构造的运行时间
- 为什么std::互斥需要很长的、非常不规则的时间来共享
- 使用Boost Interprocess创建托管共享内存需要很长时间