以天为单位的两个时间戳之间的差异 C++ [英] Difference between two timestamps in days C++
问题描述
我在 XML 文件中有格式 (Year.Month.Day) 的时间戳.
I have timestamps in the format (Year.Month.Day) in an XML file.
我需要找出两个时间戳之间的天数差异.
I need to find out the difference between two timestamps in days.
示例时间戳:
<Time Stamp="20181015">
<Time Stamp="20181012">
如何找到上述时间戳之间的天数?
How can I find the number of days between the above timestamps?
天数 = date2 - date1
.我正在考虑所有的日子(不需要跳过周末或任何其他日子).时区也无关紧要.
Number of days = date2 - date1
. I am considering all the days (don't need to skip weekends or any other day). Time-zone does not matter as well.
PS: 我知道我必须从 XML 解析时间戳.解析值后,我陷入了逻辑中.
PS: I understand that I have to parse the timestamp from XML. I am stuck in the logic after parsing value.
Update-1: std::chrono::year
和其他类似的东西是 C++20 的一部分.但是我得到一个编译错误:
Update-1: std::chrono::year
and other such things are part of C++20. But I get a compilation error:
命名空间std::chrono"没有成员year"
namespace "std::chrono" has no member "year"
推荐答案
您现在可以通过下载 Howard Hinnant 的免费开源日期/时间库.语法如下所示:
You can use C++20's syntax today (with C++11/14/17) by downloading Howard Hinnant's free, open-source date/time library. Here is what the syntax would look like:
#include "date/date.h"
#include <iostream>
#include <sstream>
int
main()
{
using namespace date;
using namespace std;
istringstream in{"<Time Stamp=\"20181015\">\n<Time Stamp=\"20181012\">"};
const string fmt = " <Time Stamp=\"%Y%m%d\">";
sys_days date1, date2;
in >> parse(fmt, date1) >> parse(fmt, date2);
cout << date2 - date1 << '\n';
int diff = (date2 - date1).count();
cout << diff << '\n';
}
输出:
-3d
-3
如果您不需要时区支持(如本示例中所示),则 date.h
是单个标头、仅限标头的库.这里是完整的文档.
If you don't need time zone support (as in this example), then date.h
is a single header, header-only library. Here is the full documentation.
如果您需要时区支持,则需要一个带有标题和源的附加库:tz.h/tz.cpp.这是时区库的文档.
If you need time zone support, that requires an additional library with a header and source: tz.h/tz.cpp. Here is the documentation for the time zone library.
这篇关于以天为单位的两个时间戳之间的差异 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!