两个日期之间的总天数
Total days between 2 dates C++
我正试图解决一个问题,要求我给出两个日期之间的总天数。
我必须处理这两个日期之间的一些问题,比如闰年和用户输入年份的方式。(例如,如果你输入1和17,代码仍然会给你16年的差(2017 - 2001 = 16)。我不应该改变main()
函数内部的任何东西。
这是我的代码。
#include <iostream>
#include <cmath>
using namespace std;
class date
{
private:
int m;
int d;
int y;
public:
date(int, int, int);
int countLeapYears(date&);
int getDifference(date&);
int operator-(date&);
};
int main()
{
int day, month, year;
char c;
cout << "Enter a start date: " << endl;
cin >> month >> c >> day >> c >> year;
date start = date(month, day, year);
cout << "Enter an end date: " << endl;
cin >> month >> c >> day >> c >> year;
date end = date(month, day, year);
int duration = end-start;
cout << "The number of days between those two dates are: " <<
duration << endl;
return 0;
}
date::date(int a, int b, int c)
{
m = a;
d = b;
y = c;
}
const int monthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31};
int date::countLeapYears(date& d)
{
int years = d.y;
if (d.m <= 2)
years--;
return years / 4 - years / 100 + years / 400;
}
int date::getDifference(date& other)
{
int n1 = other.y*365 + other.d;
for (int i=0; i<other.m - 1; i++)
{
n1 += monthDays[i];
n1 += countLeapYears(other);
}
return n1;
}
int date::operator-(date& d) {
int difference = getDifference(d);
return difference;
}
当我运行这段代码时,它显示的是invalid binary operation between "date" and "date"
。
现在,我假设当我初始化int duration = end - start
时,我应该得到一个数字。我猜我在这里做错的是我没有把(结束-开始)日期类型转换成一个整数。我认为我的函数getDifference已经解决了这个问题,但显然它没有。
接受挑战
使用这个免费的、开源的、只有头文件的日期库:
#include "date.h"
#include <iostream>
namespace me
{
class date
{
::date::sys_days tp_;
public:
date(int month, int day, int year)
: tp_{::date::year(year)/month/day}
{}
friend
int
operator-(const date& x, const date& y)
{
return (x.tp_ - y.tp_).count();
}
};
} // namespace me
using namespace std;
#define date me::date
int main()...
相关文章:
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- 日期和当前日期之间的差异
- CPP 程序二查找两个给定日期之间的天数,conol CMD
- Qml - c++ 类和 QmlRegisterType 创建的类之间的交换日期
- 十进制格式的日期之间的差异
- 解决方案在两个日期之间的天数内不起作用
- 使用 c++ 获取两个日期与时间字符串之间的差异(以秒为单位)
- 计算当前日期和用户输入日期问题之间的天数
- C 的两个日期之间的差异
- 如何使用C Win32 API计算两个日期之间的天数
- C++计算日期之间的差异
- 两个日期之间的 C++ 日期差异
- v8::值到日期之间的转换
- 两个对象之间的日期比较
- 确定日期之间的差异
- C++ 给定日期和今天日期之间的天数
- 找出日期之间的差异,并将其归类
- c++获取用户选择的日期与实际日期之间的年份(计算日、月、年)
- 两个日期之间的总天数
- 设计一个结构来存储时间和日期.写一个函数来计算两个时间之间的差(以分钟为单位)