找出日期之间的差异,并将其归类
Find the difference between the dates and group it under some category
我有一个开始日期和结束日期。我需要找出这些日期之间的差异,并将其归入以下类别。
& lt;1年,<2年,以此类推,直到X年。
我正试图为这个问题写一个unix c++程序。我可以很容易地找到unix开始和结束日期之间的时差,并与1年的时间戳(12 * 30 * 20 * 60 * 60)等进行比较。
是否有任何c++函数返回给定开始和结束日期的年份差异?同样假设,差距是8年,我想我必须这样写条件,
if((end_date - start_date) < 12 * 30 * 24 * 60 * 60)
group = " less than 1 year"
...
...
当我不知道日期之间的最大差异是多少时,我应该停在哪一点?
有没有简单的方法来计算这个?
我知道我弄糊涂了,但我已经尽我所能来解释这个问题了。提前感谢。还要注意的是,这不是赋值或者其他什么。假设"精确年份"(换句话说,所有年份都是365天)不是问题,我会这样做(在这种情况下计算每年发生的次数-因为最初的问题并没有真正说每年做什么)
const int MAX_YEARS = 10;
const int YEAR_IN_SECONDS = 365 * 24 * 60 * 60;
std::array<int, MAX_YEARS+1> bins;
int years = static_cast<int>(difftime(end_date - start_date) / YEAR_IN_SECONDS);
// Outside of range, put it at the end of range...
// We could discard or do something else in this case.
if (years > MAX_YEARS)
{
years = MAX_YEARS;
}
bins[years]++; // Seen one more of "this year".
显然,你用"箱子"做什么,以及你在那里存储什么/如何存储数据实际上取决于你真正想要实现的目标。
另一种解决方案是使用const double YEAR_IN_SECONDS = 365.25 * 24 * 60 * 60;
,它可以更好地覆盖闰年。如果你想精确一点,你必须弄清楚你是在某个能被4整除的年份的每一个闰日之前还是之后(请记住,能被100整除的年份和400的其他规则有特殊情况)。
#include <chrono>
using years = std::chrono::duration<std::chrono::system_clock::rep, std::ratio<365 * 24 * 60 * 60, 1>>;
std::chrono::system_clock::time_point end_date = std::chrono::system_clock::now();
std::chrono::system_clock::time_point start_date = end_date - years(2);
years how_many = std::chrono::duration_cast<years>(end_date - start_date);
int how_many_as_int = how_many.count();
std::cout << how_many_as_int << std::endl;
std::unordered_map<int, std::list<whatever>> m;
m[how_many_as_int].push_back(...);
相关文章:
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- 日期和当前日期之间的差异
- CPP 程序二查找两个给定日期之间的天数,conol CMD
- Qml - c++ 类和 QmlRegisterType 创建的类之间的交换日期
- 十进制格式的日期之间的差异
- 解决方案在两个日期之间的天数内不起作用
- C 的两个日期之间的差异
- 如何使用C Win32 API计算两个日期之间的天数
- C++计算日期之间的差异
- 两个日期之间的 C++ 日期差异
- v8::值到日期之间的转换
- 确定日期之间的差异
- C++ 给定日期和今天日期之间的天数
- 找出日期之间的差异,并将其归类
- c++获取用户选择的日期与实际日期之间的年份(计算日、月、年)
- 两个日期之间的总天数
- 两个日期之间的秒差
- QDate -在两个日期之间搜索
- 将R转换为Rcpp:向量中连续日期之间的平均时差
- 如何使用boost::date_time获取两个日期之间的天数