c++ - 确定日期之间的差异

标签 c++ visual-studio visual-studio-2010 visual-c++

我正在尝试为我的程序找出一种方法来获取日期(如 2003 年 2 月 2 日)并显示两者与另一个日期(如 2012 年 4 月 2 日)之间的差异,不包括闰年。到目前为止,我只能通过减去“天”来弄清楚日期是否在同一个月。在这个程序中,我使用了两组“月”、“日”和“年”整数。我不知道从哪里开始。这是我作业中完全可选的部分,但我想了解如何让它发挥作用。这对我来说似乎很麻烦,但也许有一个我没有考虑过的简单数学公式?

抱歉,我没有这部分的任何预先存在的代码,因为作业的其余部分只是处理让用户输入日期,然后添加和减去一天。

最佳答案

仅使用标准库,您就可以将一个适度疯狂的日期结构转换为从任意零点开始的秒数;然后减去并转换为天数:

#include <ctime>

// Make a tm structure representing this date
std::tm make_tm(int year, int month, int day)
{
    std::tm tm = {0};
    tm.tm_year = year - 1900; // years count from 1900
    tm.tm_mon = month - 1;    // months count from January=0
    tm.tm_mday = day;         // days count from 1
    return tm;
}

// Structures representing the two dates
std::tm tm1 = make_tm(2012,4,2);    // April 2nd, 2012
std::tm tm2 = make_tm(2003,2,2);    // February 2nd, 2003

// Arithmetic time values.
// On a posix system, these are seconds since 1970-01-01 00:00:00 UTC
std::time_t time1 = std::mktime(&tm1);
std::time_t time2 = std::mktime(&tm2);

// Divide by the number of seconds in a day
const int seconds_per_day = 60*60*24;
std::time_t difference = (time1 - time2) / seconds_per_day;    

// To be fully portable, we shouldn't assume that these are Unix time;
// instead, we should use "difftime" to give the difference in seconds:
double portable_difference = std::difftime(time1, time2) / seconds_per_day;

使用 Boost.Date_Time 不那么奇怪:

#include "boost/date_time/gregorian/gregorian_types.hpp"

using namespace boost::gregorian;
date date1(2012, Apr, 2);
date date2(2003, Feb, 2);
long difference = (date1 - date2).days();

It seems like a hassle to me, but maybe there's a simple math formula I'm not thinking about?

确实麻烦,但是有一个formula ,如果您想自己进行计算。

关于c++ - 确定日期之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9987562/

相关文章:

visual-studio - 模式比较和更新注释掉未使用的代码

C++读取带空格的字符串

c++ - 用于自定义分辨率和同步计时的 AMD API 与 NVIDIA NVAPI 的 NDA 版本是什么等效的?

java - 通过 JNI 从 Java 使用 CoreBluetooth 时未调用 didDiscoverCharacteristics

c# - Listview Itemediting 不工作

从 VS 6 到 VS 2013 的 C++ IDE 迁移

c++ - 在 C++ 中使用自定义比较函数初始化多重集

c# - 如何将从数据库检索的 smalldatetime 转换回 smalldatetime 以重新发布到数据库

string - 在 C# 中替换文件名的一部分

c# - Visual Studio Intellisense 是如何工作的?