在 C++ 中计算两个日期时间之间的差异
Calculating difference between two date-times in C++
问题总结
我有两个格式为 YYYY-MM-DD:hh:mm:ss 的字符串,我想计算它们之间的时差。比如2021-10-01:03:44:34和2021-10-01:03:44:54的区别,应该是 20 秒。然而,我得到的结果是 0.
代码
我试过以下方法:
#include <iomanip>
#include <iostream>
using namespace std;
using timestamp = time_t;
auto StringToTimestamp(const string& timeString) -> timestamp {
tm tm {};
stringstream ssBuffer(timeString);
ssBuffer >> get_time(&tm, "%Y-%b-%d:%H:%M:%S");
cout << tm.tm_year << " " << tm.tm_mon << " " << tm.tm_mday << " "
<< tm.tm_hour << " "<< tm.tm_min << " " << tm.tm_sec << " " << endl;
return mktime(&tm);
}
int main() {
string beg = {"2021-10-01:03:44:34"s};
string end = {"2021-10-01:03:44:54"s};
timestamp begTm = StringToTimestamp(beg);
timestamp endTm = StringToTimestamp(end);
double diff = difftime(endTm, begTm);
cout << "Time difference is " << diff << endl;
return 0;
}
输出
121 0 0 0 0 0
121 0 0 0 0 0
Time difference is 0
预期输出
2021 10 01 03 44 34
2021 10 01 03 04 54
Time difference is 20
为什么输出是这样的?我该如何解决这个问题?
编辑
我将这一行 "%Y-%b-%d:%H:%M:%S"
更改为 "%Y-%m-%d:%H:%M:%S"
,现在输出为
121 9 1 3 44 34
121 9 1 3 44 54
Time difference is 20
为什么年份和月份“不正确”?
您使用转换说明符%b
来获取月份,但它应该是 %m
:
ssBuffer >> get_time(&tm, "%Y-%m-%d:%H:%M:%S");
%b
- 解析月份名称,完整或缩写,例如Oct(非数字)
%m
- 将月份解析为十进制数(范围[01,12]),允许但不需要前导零
年月正确。 121 是自 1900 年以来的年数,9 是月份,从零开始 [0,11],这是为 std::tm
.
指定的
问题总结
我有两个格式为 YYYY-MM-DD:hh:mm:ss 的字符串,我想计算它们之间的时差。比如2021-10-01:03:44:34和2021-10-01:03:44:54的区别,应该是 20 秒。然而,我得到的结果是 0.
代码
我试过以下方法:
#include <iomanip>
#include <iostream>
using namespace std;
using timestamp = time_t;
auto StringToTimestamp(const string& timeString) -> timestamp {
tm tm {};
stringstream ssBuffer(timeString);
ssBuffer >> get_time(&tm, "%Y-%b-%d:%H:%M:%S");
cout << tm.tm_year << " " << tm.tm_mon << " " << tm.tm_mday << " "
<< tm.tm_hour << " "<< tm.tm_min << " " << tm.tm_sec << " " << endl;
return mktime(&tm);
}
int main() {
string beg = {"2021-10-01:03:44:34"s};
string end = {"2021-10-01:03:44:54"s};
timestamp begTm = StringToTimestamp(beg);
timestamp endTm = StringToTimestamp(end);
double diff = difftime(endTm, begTm);
cout << "Time difference is " << diff << endl;
return 0;
}
输出
121 0 0 0 0 0
121 0 0 0 0 0
Time difference is 0
预期输出
2021 10 01 03 44 34
2021 10 01 03 04 54
Time difference is 20
为什么输出是这样的?我该如何解决这个问题?
编辑
我将这一行 "%Y-%b-%d:%H:%M:%S"
更改为 "%Y-%m-%d:%H:%M:%S"
,现在输出为
121 9 1 3 44 34
121 9 1 3 44 54
Time difference is 20
为什么年份和月份“不正确”?
您使用转换说明符%b
来获取月份,但它应该是 %m
:
ssBuffer >> get_time(&tm, "%Y-%m-%d:%H:%M:%S");
%b
- 解析月份名称,完整或缩写,例如Oct(非数字)%m
- 将月份解析为十进制数(范围[01,12]),允许但不需要前导零
年月正确。 121 是自 1900 年以来的年数,9 是月份,从零开始 [0,11],这是为 std::tm
.