c++ - 如何找到两个日期之间的差异c++

标签 c++

我是一名学生,我想知道是否有人可以帮助我调试我的一个函数。对于这个程序,用户假设在 1972-2071 年之间以 mm/dd/yy 格式输入两个日期,并且该程序假设输出这两个日期之间的差异。除了计算从 1/1/72 开始的天数的函数外,我的所有函数都有效。这是我们的教授希望我们在没有额外功能的情况下做到这一点的方式。只是一个初学者版本,有很多 if else 语句和 for 循环。

int ChangeToNumber(int m, int d, int y)
{
    int total=0;

    if(y<=71) //if the year is between 2000-2071
    {
        y+=28;

        for(int i=0; i<y; i++)
        {
            if(!LeapYear(y))
            {
                total+=365;
            }
            else
            {
                total+=366;
            }
        }
    }
    else //if the year is between 1972-1999
    {
        for(int i=72; i<y; i++)
        {
            if(!LeapYear(y))
            {
                total+=365;
            }
            else
            {
                total+=366;
            }
        }
    }


    for(int i=1; i<m; i++)
    {
        total+=DaysInMonth(m, y);
    }

    total += d;
    return total;
}

最佳答案

您可以使用 std::difftime 在某些百分比上帮助您。

没有额外的功能:

http://en.cppreference.com/w/cpp/chrono/c/difftime

#include <iostream>
#include <ctime>

int main()
{
    struct std::tm a = {0,0,0,24,5,104}; /* June 24, 2004 */
    struct std::tm b = {0,0,0,5,6,104}; /* July 5, 2004 */
    std::time_t x = std::mktime(&a);
    std::time_t y = std::mktime(&b);
    if ( x != (std::time_t)(-1) && y != (std::time_t)(-1) )
    {
        double difference = std::difftime(y, x) / (60 * 60 * 24);
        std::cout << std::ctime(&x);
        std::cout << std::ctime(&y);
        std::cout << "difference = " << difference << " days" << std::endl;
    }
    return 0;
}

额外的功能:

#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();

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

相关文章:

c++ - 在快捷方式编辑器文本框中阻止应用程序级快捷方式

c++ - Visual Studio 设置以在运行时删除对 dll 文件的依赖

c++ - 从 Spy++ 窗口获取文本

c++ - 模板模板参数有哪些用途?

c++ - 如何将多个 directx LP3DXMESH 组合成 1 个网格以实现快速渲染?

c++ - filebuf::openprot 的用途是什么,它有替代品吗?

C++:从文件中读取数据以填充链表

c++ - 如何有效地将 vector 重复到cuda中的矩阵?

c++ - C++ 中的 101 Qt 样式表边距填充 hack 指南。设置填充不起作用

c++ - 从 STL std::queue 中删除而不破坏已删除的对象?